如何在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);
?>

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']);