Skip to content
Advertisement

PHP – Merge Two Associative Arrays where values match

I have two arrays that need to be merged. I can loop through each array and merge manually. But, Is there a built in function to do this?

Array 1:

Array
(
[0] => Array
    (
        [detail_image_id] => 6389
        [product_name] => Starter broadband Package
    )

[1] => Array
    (
        [detail_image_id] => 6358
        [product_name] => Starter broadband Package
    )
)

Array 2:

Array
(
[0] => Array
    (
        [detail_image_id] => 6358
        [guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
    )

[1] => Array
    (
        [detail_image_id] => 6389
        [guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
    )
)

Expected Output array is:

Array
(
[0] => Array
    (
        [detail_image_id] => 6389
        [product_name] => Starter broadband Package
        [guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
    )

[1] => Array
    (
        [detail_image_id] => 6358
        [product_name] => Starter broadband Package
        [guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
    )
)

I have added only a sample from the array. Array is huge. Is there any PHP functions like array_merge() or array_map() that we can use instead of manual for loops and iterators?

Advertisement

Answer

Older & wiser: I’ve scrubbed my answer from years earlier because I no longer recommend the techniques. It will be most succinct and efficient to merge the arrays, feed them to a foreach() loop, then “unite” (+ is used as an array union operator) data in related rows.

The null coalescing operator (??) is used to ensure that there is always something to “unite” with.

Code: (Demo)

$result = [];
foreach (array_merge($array1, $array2) as $row) {
    $result[$row['detail_image_id']] = ($result[$row['detail_image_id']] ?? []) + $row;
}

var_export(array_values($result));

Output:

array (
  0 => 
  array (
    'detail_image_id' => '6389',
    'product_name' => 'Starter broadband Package',
    'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg',
  ),
  1 => 
  array (
    'detail_image_id' => '6358',
    'product_name' => 'Starter broadband Package',
    'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg',
  ),
)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement