Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 621
IGGt Avatar asked Dec 26 '22 10:12

IGGt


2 Answers

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.

like image 83
MarcDefiant Avatar answered Jan 13 '23 12:01

MarcDefiant


The following:

$arr2 = array();
foreach ($arr1 as $a) {

  unset($a['address']);
  $key = $a['type'] . '-' . $a['part'];

  if (isset($arr2[$key])) {
    $arr2[$key]['count'] += $a['count'];
  } else {
    $arr2[$key] = $a;
  }

}
$arr2 = array_values($arr2);

Would output

array
  0 => 
    array
      'part' => string '1' (length=1)
      'type' => string '1' (length=1)
      'count' => int 15
  1 => 
    array
      'part' => string '2' (length=1)
      'type' => string '1' (length=1)
      'count' => int 10
  2 => 
    array
      'part' => string '2' (length=1)
      'type' => string '2' (length=1)
      'count' => int 5
like image 43
billyonecan Avatar answered Jan 13 '23 13:01

billyonecan