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',
  ),
)
546

Answer

Solution:

If keys of two arrays are complete the same, then you can try using funcarray_combine():

var_dump(
    array_combine(
        array_keys($arrayFirst),
        array_map(
            function(...$items) {
                return array_merge(...$items);
            },
            $arrayFirst,
            $arraySecond
        )
    )
);

Example

637

Answer

Solution:

Here is one possible workaround:

$arrayFirst = array("index" => array("keyFirst" => "valFirst"));
$arraySecond = array("index" => array("keySecond" => "valSecond"));
$result = ['index' => array_merge($arrayFirst['index'], $arraySecond['index'])];

var_dump($result);

Example

577

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)

foreach ($arrayFirst as $k => &$row) {
    $row = array_merge($row, $arraySecond[$k]);
}
var_export($arrayFirst);

People are also looking for solutions to the problem: codeigniter - PHP Array Manipulation, Invalid Argument Supplied for foreach()

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.