简体   繁体   中英

Merge two associative arrays of associative arrays and preserve all keys

How to handle a key ( index ) of a parent array? I'm getting numeric keys, but I need an index 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',
  ),
)

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

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

Example

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM