phparraysmultidimensional-arraymerge

Merge associative rows of two 2d arrays related by a shared column values


I have to multidimensional arrays like this:

array 
(
  [0] => Array
      (
        [field1] => A
        [field2] => 100
        [field3] => 20
      )

  [1] => Array
      (
        [field1] => B
        [field2] => 100
        [field3] => 30
      )
  [2] => Array
      (
        [field1] => C
        [field2] => 100
        [field3] => 30
      )
)



 array 
(
  [0] => Array
      (
        [field1b] => A
        [field2b] => 500
        [field3b] => 0
      )

  [1] => Array
      (
        [field1b] => B
        [field2b] => 300
        [field3b] => 10
      )
)

I want to merge both arrays using field1 as Key, and having in mind that arrays aren't same size.

The result array should be:

array 
(
  [0] => Array
      (
        [field1] => A
        [field2] => 100
        [field3] => 20
        [field2b] => 500
        [field3b] => 0

      )

  [1] => Array
      (
        [field1] => B
        [field2] => 100
        [field3] => 30
        [field2b] => 300
        [field3b] => 10
      )
  [2] => Array
      (
        [field1] => C
        [field2] => 100
        [field3] => 30
      )
)

Solution

  • <?php
    $array1 =  array 
    (
      "0" => Array
          (
            "field1" => "A",
            "field2" => "100",
            "field3" => "20"
          ),
    
      "1" => Array
          (
            "field1" => "B",
            "field2" => "100",
            "field3" => "30"
          ),
      "2" => Array
          (
            "field1" => "C",
            "field2" => "100",
            "field3" => "30"
          )
    );
    
    $array2 =  array 
    (
      "0" => Array
          (
            "field1b" => "A",
            "field2b" => "500",
            "field3b" => "0"
          ),
    
      "1" => Array
          (
            "field1b" => "B",
            "field2b" => "300",
            "field3b" => "10"
          )
    );
    
    $new_array1 = [];
    foreach ($array1 as $object1) {
      $new_array1[$object1['field1']] =  $object1;
    }
    
    $new_array2 = [];
    foreach ($array2 as $key => $object2) {
      $new_array2[$object2['field1b']] =  $object2;
    }
    $new_array = [];
    foreach($new_array1 as $key => $val)
    {
        $new_array[$key]['field1'] = $val['field1'];
        $new_array[$key]['field2'] = $val['field2'];
        $new_array[$key]['field3'] = $val['field3'];
        if (array_key_exists($key,$new_array2))//Check if the key is exists in an array
        {
          $new_array[$key]['field2b'] = $new_array2[$key]['field2b'];
          $new_array[$key]['field3b'] = $new_array2[$key]['field3b'];
        }       
    }
    
    print_r($new_array);
    

    DEMO

    You can try it.