问题描述
我有一个数组,它是来自两个不同数据库的两个数据库查询的组合,它看起来类似于:
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]
];
我正在寻找一种根据 part
和 type
值对数组进行分组的方法.我还需要知道分组的 count
值的总数.
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.
结果将类似于:
$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);
}
如果两个数据库都在同一台数据库服务器上,则可以使用SQLs GROUP BY
功能来做到这一点.
If both databases are on the same database server you would be able to do this using SQLs GROUP BY
feature.
这篇关于根据两列值和每一组中一列的和值对多维数组数据进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!