显示阵列会话数据时出现问题

时间:2019-01-15 12:30:42

标签: php arrays

我无法显示数组'notes'的字段,因为它不打印'addNotes'函数生成的数字。

代码将加载预加载的数据,并使用“ addNotes”函数将随机数分配给数组的“ notes”字段,最后在showStudentsList()中显示数组的数据。

<?php session_start();?>
<html>
<body>

<?php

        if(!existDataInSession()){

        initializePreloadedData();
    }

    function existDataInSession(){
        return $_SESSION['data'] != NULL;
    }

    function initializePreloadedData(){

        $person1= [
            'name' => 'person1',
            'notes' => []
        ];

        $person2= [
            'name' => 'person2',
            'notes' => []
        ];

        $data=[$person1,$person2];
        $_SESSION['data'] = $data;
    }

    function addNotes(){

        foreach ($data as $key => $value) {

            $data[$key]['notes'] = random_int(0,100);
        }
    }

    addNotes();
    showStudentsList();

    function showStudentsList(){

        $data = $_SESSION['data'];

        foreach ( $data as $student ) {

            echo $student['name'] . " ";
            echo $student['notes'];
            echo implode($student['notes']);
            echo "<br>";
        }
    }

    //Result

    //person1 Array
    //person2 Array

    ?>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果我没错理解您的要求,则$data函数中未定义addNotes()

function addNotes(){
    $data = $_SESSION['data']; // fetch data from session
    foreach ($data as $key => $value) {

        $data[$key]['notes'] = random_int(0,100);
    }
    $_SESSION['data'] = $data; // assign into session again 
}

现在仅使用无内爆的回声来获取echo $student['notes']之类的音符

希望获得帮助。

答案 1 :(得分:0)

您的代码中有几个问题。

  • 您可以在数组和整数notes之间切换。复数表示一个数组。
  • 您写入$_SESSION
  • 副本
  • $_SESSION['data'] != null在未定义时引发通知

使用notes数组的固定版本:

if(!existDataInSession()){

  initializePreloadedData();
}

addNotes();
showStudentsList();

function existDataInSession(){
  // we check if data was set. just to make double sure we check for type array as well

  return isset($_SESSION['data']) && is_array($_SESSION['data']);
}

function initializePreloadedData(){

  $person1= [
    'name' => 'person1',
    'notes' => []
  ];

  $person2= [
    'name' => 'person2',
    'notes' => []
  ];

  $_SESSION['data'] = [ $person1, $person2 ];
}

function addNotes(){

  // operate on $_SESSION referencing the value since we want to ALTER the session data

  foreach ($_SESSION['data'] as &$value) {

    // since notes was defined as an ARRAY, we append here
    $value['notes'][] = random_int(0,100);
  }
}

function showStudentsList(){

  $data = $_SESSION['data'];

  foreach ( $data as $student ) {

    echo $student['name'] . " ";
    echo implode(', ', $student['notes']);
    echo "<br>", PHP_EOL;
  }
}
相关问题