Reputation: 1356
$array = array(array("a"=>1),array("a"=>2));
I need to push data to sub array element in $array,
End result must be as follow,
Array ( [0] => Array ( [a] => 1 [b] => 2 ) [1] => Array ( [a] => 2 [b] => 2 ) )
I used following ways .
foreach($array as &$a){ $a['b']=2;}
$result = array_map("pushdata",$array);
function pushdata($a){
$a['b']=2;
}
what is the most suitable and performance high way when $array consists of more than 1000 records ?
Upvotes: 0
Views: 91
Reputation: 29991
Here is an example using array_walk()
to add a new key b
to each sub-array:
$array = array(array('a' => 1), array('a' => 2));
array_walk($array, function(&$item, $key) {
$item['b'] = 2;
});
print_r($array);
/* outputs:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[a] => 2
[b] => 2
)
)
*/
Upvotes: 1
Reputation: 508
Use array_walk , to iterate over the array and array_push to push the element to each iteration.
Upvotes: 1
Reputation: 3850
Here is an example for 5 items.
<?php
for($i = 1 ; $i<5 ; $i++){
$array[] = array("a"=>$i,"b"=>2);
}
print_r($array);
?>
Upvotes: 1