I want to add an element to every array in my multidimensional array.
My array is like this:
Array
(
[0] => Array
(
[RatingFactorPreferenceID] => 10
[PreferenceID] => 45
[RatedValue] => 1
[CreatedOn] => 1326779061
[CreatedBy] => 25
)
[1] => Array
(
[RatingFactorPreferenceID] => 20
[PreferenceID] => 45
[RatedValue] => 2
[CreatedOn] => 1326779061
[CreatedBy] => 25
)
)
I want to add [RatingID] => 2
to both arrays, then my final array would look like:
Array
(
[0] => Array
(
[RatingID] => 2
[RatingFactorPreferenceID] => 10
[PreferenceID] => 45
[RatedValue] => 1
[CreatedOn] => 1326779061
[CreatedBy] => 25
)
[1] => Array
(
[RatingID] => 2
[RatingFactorPreferenceID] => 20
[PreferenceID] => 45
[RatedValue] => 2
[CreatedOn] => 1326779061
[CreatedBy] => 25
)
)
I can loop over my array and do this, is there a better way to do this?
$array = array_map(function ($a) { return $a + array('RatingID' => 2); }, $array);
This still loops, but behind the scenes, if you prefer that.
You could also use array_walk
, but that's really just looping disguised in a different syntax.
@deceze's answer is good but instantiating a second array and using the array union operator ( +
) is needlessly complex. Keep it simple:
$new_array = array_map(
function( $inner_array ) {
$inner_array[ 'RatingID' ] = 2;
return $inner_array;
},
$orig_array
);
I think array_walk is the best option
$array = array(
array(
'RatingFactorPreferenceID' => 10,
'PreferenceID' => 45,
'RatedValue' => 1,
'CreatedOn' => 1326779061,
'CreatedBy' => 25
),
array(
'RatingFactorPreferenceID' => 20,
'PreferenceID' => 45,
'RatedValue' => 2,
'CreatedOn' => 1326779061,
'CreatedBy' => 25,
)
);
function AddAtTop(&$act_array,$key){
$act_array = array_merge(array('RatingID'=>2), $act_array);
}
array_walk($array, 'AddAtTop');
echo '<pre>';
print_r($array);
echo '</pre>';
This should work for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.