PHP嵌套数组在$ _SESSION中

时间:2014-04-22 16:52:52

标签: php session

我试图在会话变量中做一个简单的嵌套数组。但是,我很难绕过动态创建数组的逻辑。

我认为我的代码应该是什么样的(我知道这是错误的,因为我希望它是动态的):

第1页:

session_start();
$_SESSION['test'] = array();

第2页:

session_start();
$_SESSION['test'][0] = array('name' => 'john smith', 'age' => '20', 'city' => 'new york');
$_SESSION['test'][1] = array('name' => 'jane doe', 'age' => '42', 'city' => 'seattle');

我希望能够使用foreach循环来获取值

foreach($_SESSION['test'] as $test){
echo "Name " . $test['name'];
echo "Age " . $test['age'];
echo "City " . $test['city'];
}

1 个答案:

答案 0 :(得分:1)

你可以像这样推送到一个数组:

// don't include the index, just use []
$_SESSION['test'][] = array('name' => 'john smith', 'age' => '20', 'city' => 'new york');

或使用array_push()

array_push($_SESSION['test'], array('name' => 'john smith', 'age' => '20', 'city' => 'new york'));