Search code examples
phparraysmultidimensional-arraygroupingcomposite-key

Group multidimensional array data based on two column values and sum values of one column in each group


I have an array which is created as a combination of two database queries from two separate databases, it looks similar to:

$arr1 = [
    ['part' => '1', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'ccc', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'ccc', 'type' => '2', 'count' => 5]
];

I am looking for a way to group this array by part and type values. I also need to know the total of the count values as they are grouped.

The results would be something like:

$arr2 = [
    ['part' => '1', 'type' => '1', 'count' => 15],
    ['part' => '2', 'type' => '1', 'count' => 10],
    ['part' => '2', 'type' => '2', 'count' => 5]
];

but I just can't see how to do this. I have seen a few examples of grouping by a single key/value, but not by multiple values at once.


Solution

  • This function should do the job.

    function groupByPartAndType($input) {
      $output = Array();
    
      foreach($input as $value) {
        $output_element = &$output[$value['part'] . "_" . $value['type']];
        $output_element['part'] = $value['part'];
        $output_element['type'] = $value['type'];
        !isset($output_element['count']) && $output_element['count'] = 0;
        $output_element['count'] += $value['count'];
      }
    
      return array_values($output);
    }
    

    If both databases are on the same database server you would be able to do this using SQLs GROUP BY feature.