Reputation: 79
I need to merge an associative array into each row of a 2d array.
The first array is:
[
["supply_id" => 2],
["supply_id" => 4],
["supply_id" => 5],
]
The second array is:
["status" => 1, "t1_id" => 59]
The result I need is:
[
["supply_id" => 2, "status" => 1, "t1_id" => 59],
["supply_id" => 4, "status" => 1, "t1_id" => 59],
["supply_id" => 5, "status" => 1, "t1_id" => 59],
]
How can I push the associative array elements into each row?
Upvotes: 0
Views: 1260
Reputation: 47864
array_walk()
or array_map()
are native functions which are well suited for the task of merging row data with a static array.
array_map()
will iterate over the rows of the first array and merge each row with the unchanging second array data. The native function will return a new indexed array of associative rows.
Code: (Demo)
var_export(
array_map(
fn($row) => $row += $array2,
$array1
)
);
array_walk()
's third input parameter will receive the static value and the third parameter of the callback function will contain the entire passed in array.
The following snippet will modify the first array instead of generating a new result array. $i
represents the first level keys/indexes which relate to each row -- the $i
values are not used.
Code: (Demo)
array_walk(
$array1,
fn(&$row, $i, $new) => $row += $new,
$array2
);
var_export($array1);
Upvotes: 0
Reputation: 15141
Here we are using simple foreach
loop for achieving desired output.
foreach($firstArray as $key => &$value)
{
$value= array_merge($value,$secondArray);
}
print_r($array);
Upvotes: 1
Reputation: 16436
Loop through first array then merge values in new array:
$array_1= array
(
0 => array
(
"supply_id" => 2
),
1 => array
(
"supply_id" => 4
),
2 => array
(
"supply_id" => 5
),
);
$array_2=array
(
"status" => 1,
"t1_id" => 59
);
$new_array = array();
foreach ($array_1 as $key => $value) {
$new_array[] = array_merge($value,$array_2);
}
var_dump($new_array);
o/p:
array (size=3)
0 =>
array (size=3)
'supply_id' => int 2
'status' => int 1
't1_id' => int 59
1 =>
array (size=3)
'supply_id' => int 4
'status' => int 1
't1_id' => int 59
2 =>
array (size=3)
'supply_id' => int 5
'status' => int 1
't1_id' => int 59
Upvotes: 1
Reputation: 35963
you can try this:
$res = array();
foreach($secondArray as $k => $v){
$res[$k] = array_merge($secondArray[$k], $firstArray[$k]);
}
Upvotes: 2