如何正确添加key => val对现有数组

时间:2010-03-24 14:28:10

标签: php

尝试了'php.net'的例子,但不明白是什么问题。有什么建议吗?

<?php

$_SESSION['test'] = array('a' => '1', 'b' => '2');

foreach ($_SESSION['test'] as $key => $val)
    echo "key: " . $key . " val: " . $val . "\n";

// Parse error
array_push($_SESSION['test']['c'] => '3'); 

// Parse error
$_SESSION['test'][] = ('c' => '3');

foreach ($_SESSION['test'] as $key => $val)
    echo "key: " . $key . " val: " . $val . "\n";

?>

1 个答案:

答案 0 :(得分:5)

这是你在找什么?

$_SESSION['test']['c'] = '3';

[]旨在附加到数字键数组。如果在关联数组上使用它,则会产生索引(最大数字键+ 1)。