問(wèn)題描述
我有一個(gè)非常基本的問(wèn)題,但我被卡住了.我對(duì) php 很陌生,我有一個(gè)這樣的數(shù)組:
I have a pretty basic question but I am stuck. I am pretty new to php and I have an array like this:
$array = array(
'one' => 1,
'two' => array('key1' => 'val1','key2' => 'val2'),
'three' => array('key1' => 'val1','key2' => 'val2'),
'four' => array('key1' => 'val1','key2' => 'val2')
);
對(duì)于數(shù)組中的每個(gè)數(shù)組(即二"、三"和四"),我想將key3"=>val3"插入這些數(shù)組中.
and for each of the arrays in the array (that is, 'two, 'three', and 'four'), I want to insert 'key3' => 'val3' into those arrays.
我試過(guò)了:
foreach($array as $item) {
if (gettype($item) == "array") {
$item['key3'] = 'val3';
}
}
但它不起作用,我不知道為什么.到處使用各種print_r,如果我在循環(huán)中將其打印出來(lái),它似乎將'key3' => 'val3' 插入到$item 中,但原始數(shù)組似乎沒(méi)有變化.我也試過(guò)一個(gè)普通的 for 循環(huán),但也沒(méi)有用.
But it doesn't work, and I'm not sure why. Using various print_r's all over the place, it seems to insert 'key3' => 'val3' into $item if I print it out in the loop, but the original array seems unchanged. I also tried a regular for loop but that didn't work either.
推薦答案
foreach
與 $item
的副本一起使用,因此您無(wú)法修改 foreach
中的原始數(shù)組.解決此問(wèn)題的一種方法是使用 &
運(yùn)算符.
foreach
works with a copy of $item
, so you cannot modify your original array inside the foreach
. One way to work around this is to use the &
operator.
foreach($array as &$item) {
if (is_array($item)) {
$item['key3'] = 'val3';
}
}
另一種更優(yōu)雅的方法是使用 array_walk()
一個(gè)>:
Another, more elegant way would be to use array_walk()
:
array_walk($array, function (&$v, $k) {
if (is_array($v)) {
$v['key3'] = 'val3';
}
});
此示例適用于 PHP 5.3,其中引入了閉包.
This example will work from PHP 5.3, where Closures were introduced.
這篇關(guān)于php使用foreach將值插入數(shù)組中的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!