-1

I have two arrays

array1 = array(
  {'id' => '1', 'name' => 'A'},
  {'id' => '2', 'name' => 'B'},
  {'id' => '3', 'name' => 'C'},
  {'id' => '4', 'name' => 'D'}
);

array2 = array(
  {'id' => '1', 'flag' => '1'},
  {'id' => '3', 'flag' => '0'}
);

I need to merge them based on the 'id' key , so the result should be

array1 =  array(
{'id' => '1', 'name' => 'A', 'flag' => '1'},
{'id' => '2', 'name' => 'B'},
{'id' => '3', 'name' => 'C', 'flag' => '0'},
{'id' => '4', 'name' => 'D'}
);

any help ?

Naresh Kumar P
  • 4,127
  • 2
  • 16
  • 33
Fuad
  • 11
  • 1
  • 1
    I have already answered here: Check this: http://stackoverflow.com/questions/40054674/php-merge-json-arrays/40054880#40054880 – Naresh Kumar P Oct 16 '16 at 16:50
  • 1
    This question is already answered there http://stackoverflow.com/a/14843843/5788489 – Khorshed Alam Oct 16 '16 at 16:56
  • @NareshKumar.P I don't see JSON mentioned anywhere in [the question](http://stackoverflow.com/revisions/40072805/1). Please don't edit the question unless OP explicitly mentioned that. – Rajdeep Paul Oct 16 '16 at 16:57
  • Here is the solution allowing you to merge two arrays according to your rule specifying the `$idKeyName` as 3rd param. It could be `id` for you, but `hash` or `timestamp` for someone else. https://stackoverflow.com/a/60605221/2263395 – Tom Raganowicz Mar 09 '20 at 17:10

1 Answers1

0
function merge_two_arrays($array1,$array2) {
    $data = array();
    $arrayAB = array_merge($array1,$array2);
    foreach ($arrayAB as $value) {
      $id = $value['id'];
      if (!isset($data[$id])) {
        $data[$id] = array();
      }
      $data[$id] = array_merge($data[$id],$value);
    }
    return $data;
  }

$master_array = merge_two_arrays($array1,$array2);
Prakhar Agarwal
  • 2,724
  • 28
  • 31