Reputation: 529
I've 2 arrays nested to 4 or 5 levels coming from an external source (so, I can't, and don't want to manually, change the structure if possible). I've simplified the problem below but keep in mind that the structures are out of my control so I need a somewhat generic solution.
$x = array (
'one' =>
array (
'two' => 2,
'three' =>
array (
0 => 3,
),
),
);
$y = array (
'one' =>
array (
'three' =>
array (
0 => 3,
),
'four' => 4,
'five' => 5,
),
'six' => 6
);
I want to merge these and get:
array (
'one' =>
array (
'two' => 2,
'three' =>
array (
0 => 3,
),
'four' => 4,
'five' => 5,
),
'six' => 6
)
I've tried all of the following and none give me exactly the above:
var_dump($x+$y);
var_dump(array_merge($x,$y));
var_dump(array_merge_recursive($x,$y));
var_dump($y+$x);
var_dump(array_merge($y,$x));
var_dump(array_merge_recursive($y,$x));
So, I guess I need some custom code to do the merge. What would it be? Keeping it generic and simple.
Upvotes: 2
Views: 597
Reputation: 869
Use Zend\StdLib\ArrayUtils::merge(), this method is used for merging config arrays in ZF2 and do that you want.
See: https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ArrayUtils.php
Upvotes: 1
Reputation: 1849
function array_merge_recursive_unique($array1, $array2) {
if (empty($array1)) return $array2; //optimize the base case
foreach ($array2 as $key => $value) {
if (is_array($value) && is_array(@$array1[$key])) {
$value = array_merge_recursive_unique($array1[$key], $value);
}
$array1[$key] = $value;
}
return $array1;
}
Please search before post. This is a duplicate of merge-2-arrays-with-no-duplicated-keys
Upvotes: 1