1

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',
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • 4
    ['array_map()` can't handle keys](https://stackoverflow.com/questions/13036160/phps-array-map-including-keys) – Nigel Ren Mar 12 '19 at 15:14

3 Answers3

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

Jigius
  • 325
  • 4
  • 10
0

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

Antoan Milkov
  • 2,152
  • 17
  • 30
  • This answer is not explained. This is not the asker's sample data. This snippet is not suitable as a technique to generate the asker's desired output. – mickmackusa Sep 27 '22 at 08:42
0

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);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136