I'm sure there have been many questions like these in the past, so sorry if it's came up before. Basically, i'm trying to merge two multidimensional arrays whilst not creating 2 keys for any duplicate keys.
Here's an example:
$one = array(
'foo' => array(
'bar' => array(
'hello' => 'world',
'boom' => 'universe'
),
'whiz' => array(
'wham' => array(
'blam' => 'kaplow'
)
)
)
);
$two = array(
'foo' => array(
'whiz' => 'woo',
'king' => array(
'kong' => 'animal'
)
)
);
If I was to use array_merge_recursive($one, $two);
i'd get the following results:
array(1) {
["foo"]=>
array(3) {
["bar"]=>
array(2) {
["hello"]=>
string(5) "world"
["boom"]=>
string(8) "universe"
}
["whiz"]=>
array(2) {
["wham"]=>
array(1) {
["blam"]=>
string(6) "kaplow"
}
// This is the problem.
[0]=>
string(3) "woo"
}
["king"]=>
array(1) {
["kong"]=>
string(6) "animal"
}
}
}
If I were to use array_merge($one, $two);
i'd get the following results:
array(1) {
["foo"]=>
array(2) {
// This is good but the rest of the array is gone.
["whiz"]=>
string(3) "woo"
["king"]=>
array(1) {
["kong"]=>
string(6) "animal"
}
}
}
Here's the output i'm after:
array(1) {
["foo"]=>
array(3) {
["bar"]=>
array(2) {
["hello"]=>
string(5) "world"
["boom"]=>
string(8) "universe"
}
// Key is replaced, rest of the array remains intact.
["whiz"]=>
string(3) "woo"
["king"]=>
array(1) {
["kong"]=>
string(6) "animal"
}
}
}
So basically, i'm after the functionality of array_merge_recursive()
but for it to also work like array_replace_recursive()
, do you guys have any ideas?
--
I've accepted an answer for now, but don't be discouraged about showing any other possibly better methods, I will be checking back.
Thanks guys.