我有以下数组:
Array (
[0] => Array (
'id' => ...
'name' ...
),
[1] => Array (
'id' => ...
'name' ...
),
[2] => Array (
'id' => ...
'name' ...
),
[3] => Array (
'id' => ...
'name' ...
),
)
我想要做的是为每个子数组添加相同的pid
键值对。是否有一种简单的方法可以在不必执行foreach
的情况下执行此操作?
答案 0 :(得分:1)
无需明确使用foreach
或其他类型的循环,您可以使用PHP的array_map
函数。虽然这将在引擎盖下执行迭代循环,但它将返回一个数组,其中每个元素都由您的函数处理。
<?php
$arr = Array (
0 => Array (
'id' => 1,
'name' => 'one'
),
1 => Array (
'id' => 2,
'name' => 'two'
),
2 => Array (
'id' => 3,
'name' => 'three'
),
3 => Array (
'id' => 4,
'name' => 'four'
)
);
function append_pid_kvpair($n){
$n ['pid']= 'value';
return $n;
}
$arr = array_map("append_pid_kvpair",$arr);
echo "<pre>".print_r($arr,true)."</pre>";
将导致此输出
Array
(
[0] => Array
(
[id] => 1
[name] => one
[pid] => value
)
[1] => Array
(
[id] => 2
[name] => two
[pid] => value
)
[2] => Array
(
[id] => 3
[name] => three
[pid] => value
)
[3] => Array
(
[id] => 4
[name] => four
[pid] => value
)
)