1
<?php
$array = array(array(1,2,3), array(4,2,5), array(5,25,2));
foreach($array as $ar){
  $ar['test'] = 'test';
}
print_r($array);

http://codepad.org/FclkyyFa

为什么这不起作用?我想使用 foreach 并为每个子数组测试值添加。我怎样才能做到?

4

2 回答 2

0

您需要将其分配给array('test' => 'test').

于 2012-11-14T12:18:16.480 回答
0

@air4X 的评论是对的。用于&创建对实际数组的引用,然后将值设置为:

foreach($array as &$ar) {
    // if you want to create an associative element called 'test'        
    $ar['test'] = 'test'; 
    // if you simply want to add the value 'test' to each array
    $ar[] = 'test';
}
于 2012-11-14T12:25:05.427 回答