php使用foreach将值插入数组中

2021-12-26 00:00:00 arrays loops foreach php associative-array

我有一个非常基本的问题,但我被卡住了.我对 php 很陌生,我有一个这样的数组:

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

对于数组中的每个数组(即二"、三"和四"),我想将key3"=>val3"插入这些数组中.

and for each of the arrays in the array (that is, 'two, 'three', and 'four'), I want to insert 'key3' => 'val3' into those arrays.

我试过了:

foreach($array as $item) {
    if (gettype($item) == "array") {
        $item['key3'] = 'val3';
    }
}

但它不起作用,我不知道为什么.到处使用各种print_r,如果我在循环中将其打印出来,它似乎将'key3' => 'val3' 插入到$item 中,但原始数组似乎没有变化.我也试过一个普通的 for 循环,但也没有用.

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 的副本一起使用,因此您无法修改 foreach 中的原始数组.解决此问题的一种方法是使用 & 运算符.

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';
    }
}

另一种更优雅的方法是使用 array_walk():

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.

相关文章