PHP插入值转换成使用的foreach数组的数组 [英] php insert value into array of arrays using foreach

查看:136
本文介绍了PHP插入值转换成使用的foreach数组的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pretty基本的问题,但我坚持。我是pretty新的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'到$项目,如果我在循环打印出来,但原来的排列并没有什么改变。我也尝试了常规的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 $项目,副本的作品,所以你不能修改的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()

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.

这篇关于PHP插入值转换成使用的foreach数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆