php php使用foreach将值插入数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16491704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:13:02  来源:igfitidea点击:

php insert value into array of arrays using foreach

phparraysloopsforeachassociative-array

提问by Benjamin Thvedt

I have a pretty basic question but I am stuck. I am pretty new to php and I have an array like this:

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

$array = array(
    'one' => 1,
    'two' => array('key1' => 'val1','key2' => 'val2'),
    'three' => array('key1' => 'val1','key2' => 'val2'),
    'four' => array('key1' => 'val1','key2' => 'val2')
);

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

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

I tried this:

我试过这个:

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

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.

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

回答by kapa

foreachworks 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与 的副本一起使用$item,因此您无法修改foreach. 解决此问题的一种方法是使用&运算符。

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

Another, more elegant way would be to use array_walk():

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

array_walk($array, function (&$v, $k) { 
    if (is_array($v)) {
        $v['key3'] = 'val3';
    }
});

This example will work from PHP 5.3, where Closures were introduced.

这个例子适用于 PHP 5.3,其中引入了闭包。

回答by hek2mgl

PHP has a function to check whether a variable is an array or not: is_array(). Use this:

PHP 有一个函数来检查一个变量是否是一个数组:is_array(). 用这个:

if (is_array($item)) { ...

回答by Asad

while looping with foreach use key like :

使用 foreach 循环时使用键,例如:

foreach($array as $key => $item){

    $array[$key]['newElement'] = "newValue";

}