dongyuanguang3893 2016-06-05 05:11
浏览 50

如何在PHP中添加和访问会话中的数组

I am new with php. I want store multidimensional associative array in session and also fetch the value of array from session. But I am not able to do this properly. Below is my code. Thanks.

$myArray = array();
if ((!isset($_SESSION['game']))) {
    echo 'the session is either empty or doesn\'t exist';
} else {
    $myArray = unserialize($_SESSION['game']);
}





    array_push($myArray, new MapResult($keyId, $colorCode, 'NP', $highlow, 'NP', $evenOdd, 'NP'));



session_start();
$_SESSION['game'] = serialize($myArray);
?>
  • 写回答

1条回答 默认 最新

  • doulian8742 2016-06-05 05:18
    关注

    You can't access $_SESSION variables before calling session_start. Also, your serializing of the data is probably pointless. Session data is stored server-side. Serializing would be used if you wanted to dump the session state to a file or to a database or something.

    A word of advice...

    Instead of littering your code with $_SESSION references, it helps to wrap access in reusable functions. Your code will look nicer and you'll be free to change how session data is stored/accessed at any time without having to refactor your entire app.

    // must be called before reading/writing $_SESSION
    session_start();
    
    function session_is_initialized() {
      return isset($_SESSION['game']);
    }
    
    function session_setup() {
      $_SESSION['game'] = [/* some initial data */];
    }
    
    function session_add_item($item) {
      array_push($_SESSION['game'], /* more data */);
    }
    

    Now you can write nice clean code

    if (!session_is_initialized()) {
      session_setup();
    }
    session_add_item(['some', 'data']);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等