<?php
$array1 = [
'fruits' => [
'apple' => 'red',
'banana' => 'yellow'
],
'numbers' => [1, 2]
];
$array2 = [
'fruits' => [
'orange' => 'orange',
'apple' => 'green' // Should overwrite 'red'
],
];
$array3 = [
'numbers' => [2, 3, 4], // Should extend, not replace
'colors' => ['blue', 'purple'] // New key should be added
];
function mergeNestedArraysInefficient(array $array, array ...$otherArrays) {
foreach ($otherArrays as $other) {
if (array_is_list($other)) {
$array = array_values(array_unique(array_merge($array, $other)));
continue;
}
foreach ($other as $k => $v) {
if (is_array($v) && key_exists($k, $array)) {
$array[$k] = mergeNestedArraysInefficient($array[$k], $v);
} else {
$array[$k] = $v;
}
}
}
return $array;
}
var_export(mergeNestedArraysInefficient($array1, $array2, $array3));
- Output for 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array (
'fruits' =>
array (
'apple' => 'green',
'banana' => 'yellow',
'orange' => 'orange',
),
'numbers' =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
),
'colors' =>
array (
0 => 'blue',
1 => 'purple',
),
)
preferences:
65.33 ms | 407 KiB | 5 Q