我有一个Array,它是作为两个独立数据库的两个数据库查询的组合创建的,它看起来类似于:
$arr1[0] = array('part' => '1', 'address' => 'aaa', 'type' => '1', 'count' => 5);
$arr1[1] = array('part' => '1', 'address' => 'bbb', 'type' => '1', 'count' => 5);
$arr1[2] = array('part' => '1', 'address' => 'ccc', 'type' => '1', 'count' => 5);
$arr1[3] = array('part' => '2', 'address' => 'aaa', 'type' => '1', 'count' => 5);
$arr1[4] = array('part' => '2', 'address' => 'bbb', 'type' => '1', 'count' => 5);
$arr1[5] = array('part' => '2', 'address' => 'ccc', 'type' => '2', 'count' => 5);
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种通过'part'和'type'对这个数组进行分组的方法.我还需要知道它们被分组的总数"计数".
结果将是这样的:
$arr2[1] = array('part' => '1', 'type' => '1', 'count' => 15);
$arr2[2] = array('part' => '2', 'type' => '1', 'count' => 10);
$arr2[3] = array('part' => '2', 'type' => '2', 'count' => 5);
Run Code Online (Sandbox Code Playgroud)
但我只是看不出怎么做.我已经看到了一些按单个键/值分组的示例,但不是多个分组.
如果有人能够对此有所了解,那将非常感激.
这个功能应该可以胜任.
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);
}
Run Code Online (Sandbox Code Playgroud)
如果两个数据库位于同一数据库服务器上,则可以使用SQL GROUP BY功能执行此操作.