我有一个二维数组:
$test = array(
"foo" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"bar" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"baz" => array(
'a' => 1,
'b' => 2,
'c' => 3
)
);
我想在外部数组的每个元素中添加一个名为'd'
且值为4
的字段,以便生成的数组变为:
array(
"foo" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
),
"bar" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
),
"baz" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
)
)
我试过这个:
foreach ( $test as $elem )
{
$elem['d'] = 4;
}
哪个不起作用。我做错了什么,我怎样才能做到这一点?
答案 0 :(得分:9)
数组和基元在PHP中通过值传递(尽管对象通过引用传递)。在foreach
循环中克服此问题的一种方法是通过循环中的引用访问子数组:
// Call $elem by reference with &
foreach ( $test as &$elem ) {
$elem['d'] = 4;
}
print_r($test);
array(3) {
["foo"]=>
array(4) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
["d"]=>
int(4)
}
...
}
答案 1 :(得分:3)
$test = array(
"foo" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"bar" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"baz" => array(
'a' => 1,
'b' => 2,
'c' => 3
)
);
foreach($test as $key => $val)
$test[$key]['d'] = 4;
print_r($test);
答案 2 :(得分:0)
你可以利用php函数和回调:
array_walk($test, function ( & $value) {
$value['d'] = 4;
});