-3
I have following 2 arrays:

$arr1 = [
   0 => [
      'id' => 1,
      'name' => 'Peter',
   ],
   1 => [
      'id' => 2,
      'name' => 'John',
   ]
]

$arr2 = [
   0 => [
      'id' => 1,
      'surname' => 'Newman',
   ],
   1 => [
      'id' => 2,
      'surname' => 'Cena',
   ]
]

What I want to do is merge these arrays referencing on the same key. In this case I would like to merge them where the id is matching. So the output I would expect would be:

$finalArr = [
       0 => [
          'id' => 1,
          'name' => 'Peter',
          'surname' => 'Newman',
       ],
       1 => [
          'id' => 2,
          'name' => 'John',
          'surname' => 'Cena',
       ]
    ]

I am using laravel but the language should not matter too much. I would like to use collections if possible.

Epsilon47
  • 768
  • 1
  • 13
  • 28

3 Answers3

1

You could use array_map and array_merge and check if the keys match:

$finalArr = array_map(function($x) use ($arr2) {
    foreach($arr2 as $b) {
        if ($x["id"] === $b["id"]) {
            return array_merge($x, $b);
        }
    }
    return $x;
}, $arr1);

var_dump($finalArr);

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Try this one:

foreach ($arr2 as $key2 => $value2) {
    foreach ($arr1 as $key1 => $value1) {
        if($value2['id'] == $value1['id']){
            $arr1[$key1] = array(
                'id' =>  $value1['id'],
                'name' => $value1['name'],
                'surname' => $value2['surname']
            );
        }
    }
}
0
$arr1 = [
  0 => [
    'id' => 1,
    'name' => 'Peter',
  ],
  1 => [
    'id' => 2,
    'name' => 'John',
  ]
];

$arr2 = [
  0 => [
    'id' => 1,
    'surname' => 'Newman',
  ],
  1 => [
    'id' => 2,
    'surname' => 'Cena',
  ]
];

// First, I create a new array
$new_array = array();

// Now I loop throught first array and merge each array by key
foreach ($arr1 as $key => $value) {
    // If I just check if second array has the key so you can merge both
    // If you are 100% sure that both array has same key, no need to use isset()
    if (isset($arr2[$key])) {
        $new_array[$key] = array_merge($arr1[$key], $arr2[$key]);
    }
}

var_dump($new_array);

Output is :

array (size=2)
  0 => 
    array (size=3)
      'id' => int 1
      'name' => string 'Peter' (length=5)
      'surname' => string 'Newman' (length=6)
  1 => 
    array (size=3)
      'id' => int 2
      'name' => string 'John' (length=4)
      'surname' => string 'Cena' (length=4)
Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36