在一个阵列使用的foreach更新阵列 [英] Updating arrays in an array using foreach
问题描述
我想更新数组,但该数组包含数组。
I'm trying to update an array but the array contains arrays.
对于例如,
$data = array(
array('name'=>'John','age'=>'19','alive'=>'false'),
array('name'=>'Bob','age'=>'32','alive'=>'false'),
array('name'=>'Kate','age'=>'22','alive'=>'false'),
);
我需要另一个元素添加到所有这些阵列。
I need to add another element to all these arrays.
我尝试使用的foreach
I tried using foreach
foreach($data as $onearray){
$onearray['alive'] = 'true';
}
我是否需要创建一个新的数组,并添加所有更新阵列回新的?
Do I need to create a new array and add all updated arrays back to new one?
推荐答案
使用引用:
foreach($data as &$onearray) {
$onearray['alive'] = 'true';
}
unset($onearray)
和清理参考算账,进一步code不会搞砸了。
and clean up the reference afterwards, so further code will not mess it up
为了能够直接修改环路内的数组元素
与&放precede $值;.在这种情况下,该值将被分配
参考。
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
看到更多的foreach参考: HTTP://us2.php .NET /手动/ EN /控制structures.foreach.php
see foreach-reference for more: http://us2.php.net/manual/en/control-structures.foreach.php
这篇关于在一个阵列使用的foreach更新阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!