Reputation: 638
How I can merge/push one array to another to specific keys? Here are my arrays:
// Array 1
Array
(
[1] => Array
(
[name] => test
)
)
// Array 2
Array
(
[1] => Array
(
[age] => 25
)
)
I want this result:
Array
(
[1] => Array
(
[name] => test
[age] => 25
)
)
Upvotes: 0
Views: 50
Reputation: 40653
$arr = [ 1 => [ "name" => "Test" ] ];
$arr2 = [ 1 => [ "age" => 25 ] ];
foreach ($arr as $key => $value) {
if (isset($arr2[$key])) {
$arr[$key] = array_merge($value,$arr2[$key]);
}
}
print_r($arr);
Upvotes: 1
Reputation: 47864
You can traverse the first array and use the array union assignment operator and the null coalescing operator to append related values from the second array to the first array. Demo
foreach ($arr1 as $k => &$v) {
$v += $arr2[$k] ?? [];
}
var_export($arr1);
Upvotes: 0
Reputation: 1282
Just add them together:
<?php
$array1 = array('name' => 'test');
$array2 = array('age' => 21);
var_dump($array1 + $array2);
Upvotes: -1