Search code examples
phparraysmultidimensional-arrayduplicatesarray-merge

Combine two 2d arrays and have duplicate rows removed


How do I create a new multidimensional array by merging two arrays and removing any duplicate rows.

First array:

[
    0 => ["id" => "0001", "name" => "sample name 1"],
    1 => ["id" => "0002", "name" => "sample name 2"],
    3 => ["id" => "0003", "name" => "sample name 3"]
]

Second Array:

[
    0 => ["id" => "0002", "name" => "sample name 2"],
    1 => ["id" => "11323", "name" => "blah blah"]
]

The desired result is:

[
    ["id" => "0001", "name" => "sample name 1"],
    ["id" => "0002", "name" => "sample name 2"],
    ["id" => "0003", "name" => "sample name 3"]
    ["id" => "11323", "name" => "blah blah"]
]

Solution

  • You can do this

    $array1 = Array(
            0 => Array("id" => "0001","name" => "sample name 1"),
            1 => Array("id" => "0002","name" => "sample name 2"),
            3 => Array("id" => "0003","name" => "sample name 3"));
    
    $array2 = Array(
            0 => Array("id" => "0002","name" => "sample name 2"),
            1 => Array("id" => "11323","name" => "blah blah"));
    
    $output = array_map("unserialize", array_unique(array_map("serialize", array_merge($array1,$array2))));
    
    var_dump($output);
    

    Output

    array
      0 => 
        array
          'id' => string '0001' (length=4)
          'name' => string 'sample name 1' (length=13)
      1 => 
        array
          'id' => string '0002' (length=4)
          'name' => string 'sample name 2' (length=13)
      2 => 
        array
          'id' => string '0003' (length=4)
          'name' => string 'sample name 3' (length=13)
      4 => 
        array
          'id' => string '11323' (length=5)
          'name' => string 'blah blah' (length=9)