4

How can I merge these two array together?

Array
(
[0] => Array
    (
        [id] => 5
        [cnt] => 14
    )

[1] => Array
    (
        [id] => 8
        [cnt] => 2
    )

)

Array
(
    [0] => Array
        (
            [id] => 8
            [binding] => hardcover
        )

    [1] => Array
        (
            [id] => 5
            [binding] => softcover
        )
)

The expected result is:

Array
    (
        [0] => Array
            (
                [id] => 5
                [binding] => softcover
                [cnt] => 14
            )

        [1] => Array
            (
                [id] => 8
                [binding] => hardcover
                [cnt] => 2
            )

    )

The merge of these two array should happen on the [id] value and not on any sort of the array. How can I do this with php in a fast way?

Stefan
  • 359
  • 3
  • 17

2 Answers2

8
$output = array();

$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
  $id = $value['id'];
  if ( !isset($output[$id]) ) {
    $output[$id] = array();
  }
  $output[$id] = array_merge($output[$id], $value);
}

var_dump($output);

Optionally if you want to reset output's keys, just do:

$output = array_values($output);
hsz
  • 148,279
  • 62
  • 259
  • 315
  • If I did NOT know the number of arrays ( `$arrayA`, `$arrayB`, ..., etc) ahead of time, how does the `array_merge` part go in that case? – Ifedi Okonkwo May 19 '19 at 18:34
0
  1. Merge the input arrays, then
  2. Loop the rows and merge associative row data with the array union operator (+). The array union operator should only be used with associative, non-numeric keyed arrays.

The first time that a given id is encountered, there will be no "group" in the result array yet. To avoid a Warning generated by trying to merge row data with an undeclared variable, use the null coalescing operator (??) to fallback to an empty array.

The snippet below will be highly efficient because it makes no iterated function calls.

If you do not want the first level keys in the result array, then call array_values() to re-index the array.

Code: (Demo)

$a1 = [
    ['id' => 5, 'cnt' => 14],
    ['id' => 8, 'cnt' => 2],
];
$a2 = [
    ['id' => 8, 'binding' => 'hardcover'],
    ['id' => 5, 'binding' => 'softcover'],
];

$result = [];
foreach (array_merge($a1, $a2) as $row) {
    $result[$row['id']] = ($result[$row['id']] ?? []) + $row;
}
var_export(array_values($result));

Output:

array (
  0 => 
  array (
    'id' => 5,
    'cnt' => 14,
    'binding' => 'softcover',
  ),
  1 => 
  array (
    'id' => 8,
    'cnt' => 2,
    'binding' => 'hardcover',
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136