I have two n-dimensional arrays which I would like to merge. I have already reviewed this question, however, it is only good for merging two dimensional arrays. I am trying to accomplish the same thing, except with two n-dimensional arrays.
So, for example:
Array 1:
Array (
[''] => 'ID One'
['foo'] => Array (
[''] => 'ID Two'
['bar'] => 'ID Three'
)
)
Array 2:
Array (
['foo'] => Array (
['bar'] => Array (
['baz'] => 'ID Four'
)
)
['bax'] => 'ID Five'
)
Desired Array Result:
Array (
[''] => 'ID One'
['foo'] => Array (
[''] => 'ID Two'
['bar'] => Array (
[''] => 'ID Three'
['baz'] => 'ID Four'
)
)
['bax'] => 'ID Five'
)
Although this is a demonstration of what I am trying to achieve, when it is being used for some web apps, it is entirely possible that it will have 10, perhaps even 15 nested arrays. So, how can Array 1 and Array 2 be merged to form the Desired Array Result?
Conveniently, array_merge_recursive
does exactly that!
This demo covers the cases.
Try array_merge_recursive()
or array_replace_recursive()
.
If neither of those functions does what you want, it's still easy to do with a recursive function, e.g.:
function merge($a, $b) {
foreach ($b as $key => $value) {
if (!is_array($value) {
$a[$key] = $value;
} else if (isset($a[$key])) {
$a[$key] = merge($a[$key], $value);
} else {
$a[$key] = $value;
}
}
return $a;
}
$merged = merge($a, $b);