>我正在尝试更新数组,但数组包含数组。
举个例子,
$data = array(
array('name'=>'John','age'=>'19','alive'=>'false'),
array('name'=>'Bob','age'=>'32','alive'=>'false'),
array('name'=>'Kate','age'=>'22','alive'=>'false'),
);
我需要向所有这些数组添加另一个元素。
我试过使用 foreach
foreach($data as $onearray){
$onearray['alive'] = 'true';
}
我是否需要创建一个新阵列并将所有更新的数组添加回新阵列?
您是否尝试使用数据数组键?这样:
foreach($data as $key => $onearray){
$data[$key]['alive'] = 'true';
}
(注意$onearray永远不会被使用)
更快的是:
for($i = 0; $i < count($data); $i++) {
$data[$i]['alive'] = 'true';
}
使用引用:
foreach($data as &$onearray) {
$onearray['alive'] = 'true';
}
unset($onearray)
并在之后清理引用,因此进一步的代码不会弄乱它
<小时 />为了能够直接修改循环中的数组元素 在 $value 前面加上 &。在这种情况下,该值将由 参考。
请参阅参考以获取更多信息:http://us2.php.net/manual/en/control-structures.foreach.php
使用内置函数 array_walk — 将用户函数应用于数组的每个成员
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2<br />n";
}
echo "Before ...:n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:n";
array_walk($fruits, 'test_print');
?>
输出
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple