0

This is not a duplicate of the following questions:

array merge with same key in php

PHP Merge array with same keys and one same value

PHP array merge elements with same key

Say I have two arrays:

   $A = [
        0 => [
            'id' => 10001,
            'name' => 'John'
        ],
        1 => [
            'id' => 10002,
            'name' => 'Jack'
        ]
    ];

    $B = [
        0 => [
            'id' => 10001,
            'count' => 4
        ],
        2 => [
            'id' => 10002,
            'count' => 6
        ]
    ];

What I'm expecting result after merging is like this:

   $C = [
        1 => [
            'id' => 10001,
            'name' => 'John',
            'count' => 4
        ],
        2 => [
            'id' => 10002,
            'name' => 'Jack',
            'count' => 6
        ]
    ]; 

Right now what I'm doing is loop two arrays, find the same key, and add the 'count' after to 'name'. It works, but since these two arrays are big, there may be another way that is more efficient and elegant.

Any suggestion would be appreciated!

Jack
  • 170
  • 2
  • 15
  • You don't seem to be merging by keys, you're merging by `id`. The keys are `0`, `1`, and `2`. That's why your duplicates are not helpful, they're answering a different question. – Barmar Aug 20 '22 at 17:49
  • If your code works and need some optimization, you should ask for code review at https://codereview.stackexchange.com/ – Markus Zeller Aug 20 '22 at 17:50
  • You should turn one of the arrays into an associative array whose keys are the `id` values. Then you won't need a second loop to find the matching id. – Barmar Aug 20 '22 at 17:52
  • Does this answer your question? [php combine two array's subarrays where value of certain key is equal](https://stackoverflow.com/questions/61392697/php-combine-two-arrays-subarrays-where-value-of-certain-key-is-equal) – Cornel Raiu Aug 21 '22 at 00:47
  • are the ids unique? – Cornel Raiu Aug 21 '22 at 00:50
  • https://stackoverflow.com/a/72330890/2943403 – mickmackusa Aug 21 '22 at 03:57

0 Answers0