Search code examples
phparraysmultidimensional-arraymappingassociative-array

Merge associative row data from a 2d array to another 2d array on shared id column values


I have two associative array having one value in common, like

$array1 = [
    ["ID" => "AAAA", "Name" => "Apple"],
    ["ID" => "BBBB", "Name" => "Avocado"],
    ["ID" => "CCCC", "Name" => "Banana"]
];

$array2 = [
    [
        "ID" => "AAAA",
        "Taste" => "Yumi",
        "Location" => "France",
        "Price" => "Cheap"
    ],
    [
        "ID" => "CCCC",
        "Taste" => "Yumi",
        "Location" => "Africa",
        "Price" => "Cheap"
    ],
    [
        "ID" => "BBBB",
        "Taste" => "Yumi",
        "Location" => "America",
        "Price" => "Expensive"
    ],
    [
        "ID" => "HZGA",
        "Taste" => "Berk",
        "Location" => "Moon",
        "Price" => "Expensive"
    ]
];

I would like to merge them both by their ID. A simple merge isn't possible because they arn't sorted, have 40.000 + values and don't have the same size.

I planned to use a double foreach, and create a third array were the ID was common, I dropped the idea. Since having to parse 40.000 values in the first array for each of the 40.000 values from the second array take too long.

Is there some solution ? I would like to having it look like this at final :

ArrayFinal (
  [0]=>
  array(4) {
    ["ID"]=> "AAAA"
    ["Name"]=> "Apple"
    ["Taste"]=> "Yumi"
    ["Location"]=> "France"
    ["Price"]=> "Cheap"
  }
  [1]=>
  array(4) {
    ["ID"]=> "CCCC"
    ["Name"]=> "Banana"
    ["Taste"]=> "Yumi"
    ["Location"]=> "Africa"
    ["Price"]=> "Cheap"
  }
  [3]=>
  array(4) {
    ["ID"]=> "BBBB"
    ["Name"]=> "Avocado"
    ["Taste"]=> "Yumi"
    ["Location"]=> "America"
    ["Price"]=> "Expansive"
  }
)

Solution

  • You cannot avoid to loop. But foreach is pretty fast. Tested on an array of 50.000 and it took 0.04 seconds.

    What this wil do is:

    • create a TMP array
    • get the KEY and ID values from ARRAY1
    • put them as 'ID'=>key in the TMP array
    • loop ARRAY2, get the ID
    • look up the corresponding ID in TMP
    • get the key from ARRAY1
    • merge ARRAY1 and ARRAY2

    You'll end up with ARRAY1 having the data from ARRAY2

    $ar1=[...]; //original array 1
    $ar2=[...]; //original array 2
    
    // get ID=> key pairs
    $kv=[];
    foreach($ar1 as $k => $v){
        $kv[ $v['id'] ] = $k;
        }
    
    // loop ARRAY2
    foreach($ar2 as $k => $v){
        if( array_key_exists( $v['id'] , $kv ) ){
            $ar1[ $kv[$v['id']] ] = array_merge( $ar1[$kv[$v['id']]] , $ar2[$k] );
            }
        }