The function array_replace_recursive
will do what you describe. The problem with array_merge_recursive
is that when it encounters sequential arrays, it concatenates the values of the merged arrays, rather than overwriting those entries with the same index. array_replace_recursive
is essentially the same thing but always treats arrays as associative and never concatenates them.
http://php.net/manual/en/function.array-replace-recursive.php
Since your leaf nodes are all stdObject
s and array_merge_recursive
won't merge objects, you will need to convert them to arrays first.
Example:
<?php
$a = [
'entries' => [
(object) [
'title' => 'Alpha',
'id' => 'Alpha ...'
],
(object) [
'title' => 'Beta',
'id' => 'Beta ...'
]
]
];
$b = [
'entries' => [
(object) [
'artistName' => 'Alpha artist',
'feedUrl' => 'fdsfsdf'
],
(object) [
'artistName' => 'Beta artist',
'feedUrl' => 'gfdsgfds'
]
]
];
function convert_objects($array) {
array_walk_recursive($array, function(&$value) {
$value = (array) $value;
});
return $array;
}
var_export(array_replace_recursive(convert_objects($a), convert_objects($b)));
Which prints:
array (
'entries' =>
array (
0 =>
array (
'title' => 'Alpha',
'id' => 'Alpha ...',
'artistName' => 'Alpha artist',
'feedUrl' => 'fdsfsdf',
),
1 =>
array (
'title' => 'Beta',
'id' => 'Beta ...',
'artistName' => 'Beta artist',
'feedUrl' => 'gfdsgfds',
),
),
)