php - Merge two associative arrays of associative arrays and preserve all keys
32
How to handle a key (index
) of a parent array? I'm getting numeric keys, but I need anindex
as a key.
Example.
Sample input:
$arrayFirst = [
"index" => ['a' => '1'],
['a' => '2']
];
$arraySecond = [
"index" => ['b' => '1'],
['b' => '2']
];
My code:
var_export(
array_map(
function(...$items) {
return array_merge(...$items);
},
$arrayFirst,
$arraySecond
)
);
Incorrect/Current output:
array (
0 =>
array (
'a' => '1',
'b' => '1',
),
1 =>
array (
'a' => '2',
'b' => '2',
),
)
Desired output:
array (
'index' =>
array (
'a' => '1',
'b' => '1',
),
0 =>
array (
'a' => '2',
'b' => '2',
),
)
Answer
Solution:
If keys of two arrays are complete the same, then you can try using func
array_combine()
:Example
Answer
Solution:
Here is one possible workaround:
Example
Answer
Solution:
I recommend only looping on the second array and directly modifying the first array. Of course, if you don't want to modify the first array, you can make a copy of it and append the second array's data to that.
Anyhow, using a classic loop to synchronously merge the two arrays will be more performant, readable, and maintainable than a handful of native function calls.
Code: (Demo)