phparraysmultidimensional-arraymergegrouping

Group and merge rows in a 2d arrays if they have the same column value


I have an array of associative arrays.

$array = [
    ['report_date' => 'date', 'name' => 'name'], 
    ['report_date' => 'date', 'color' => 'color']
];

I want to consolidate this array and if

$array[x]['report_date'] === $array[y]['report_date']

then I need to perform a merge that would return in this case:

$newArray = [['report_date' => date, 'name' => name, 'color' => color]]

Of course we would need to take into account that there may be multiple arrays that fulfill this requirement and we would have to merge them as well.

I've tried a couple of things, that resulted in mapping and foreach merges that took forever to process and in the end couldn't get it working.


Solution

  • You can create a new array, indexed by report_date and push the values into it:

    $out=[];
    foreach($array as $subarray){
        foreach($subarray as $key=>$val){
            $out[$subarray['report_date']][$key]=$val;
        }
    }
    
    var_dump($out);