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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With