douke3007 2014-04-22 16:52
浏览 27
已采纳

PHP嵌套数组在$ _SESSION中

I'm trying to do a simple nested array in a session variable. But I'm having a hard time wrapping my head around the logic for the dynamic creation of the arrays.

What I think my code should look like (which I know is wrong, because I want it to be dynamic):

Page 1:

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

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

I want to be able to do a foreach loop to grab the values

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

1条回答 默认 最新

  • dongronge3732 2014-04-22 16:56
    关注

    You can push to an array like so:

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

    Or using array_push():

    array_push($_SESSION['test'], array('name' => 'john smith', 'age' => '20', 'city' => 'new york'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法