php insert value into array of arrays using foreach(php使用foreach将值插入数组中)
问题描述
我有一个非常基本的问题,但我被卡住了.我对 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.
这篇关于php使用foreach将值插入数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php使用foreach将值插入数组中
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01