将多维数组按一列分组,并对另一列求和


Group multidimensional array by one column and sum the other column

我有一个数组,其中包含带有键和值对的关联子数组。

数组的格式如下:

$info = [
    ['name1' => 'type1', 'count' => '27'],
    ['name1' => 'Type2', 'count' => '11'],
    ['name1' => 'Type1', 'count' => '5'],
    ['name1' => 'Type1', 'count' => '12'],
    ['name1' => 'type2', 'count' => '10']
];

我如何对"name1"键的每个值的"count"键中的值求和,这样我就会得到这样的计数结果?

 ['type1' => 44, 'type2' => 22]
$new   = array();
foreach ($info as $v)
{
    // Normalize the key names
    $key = ucfirst($v['name1']);
    if (isset($new[$key]))
    {
        $new[$key] += $v['count'];
    }
    else
    {
        $new[$key] = $v['count'];
    }
}

那么print_r($new);会给你这个:

Array
(
    [Type1] => 44
    [Type2] => 21
)

这是我的看法。

function getTypeArray($arr, $type) {
    return array_filter($arr, function($item) use($type) {
        return strtolower($item['name1']) == $type;
    });
}
function sumArray($arr) {
    return array_sum(array_map(function($item) {
        return $item['count'];
    }, $arr));
}
$type1_count = sumArray(getTypeArray($info, 'type1'));
$type2_count = sumArray(getTypeArray($info, 'type2'));
print 'Type1: '.$type1_count;
print 'Type2: '.$type2_count;

最明显的解决方案是迭代数组:

$counts = array();
foreach($info as $elem){
    $counts[$elem['name1']] += $elem['count'];
}
var_dump($counts);

输出:

Warning: Undefined array key "type1"
Warning: Undefined array key "Type2"
Warning: Undefined array key "Type1"
Warning: Undefined array key "type2"
array(4) {
  ["type1"]=>
  int(27)
  ["Type2"]=>
  int(11)
  ["Type1"]=>
  int(17)
  ["type2"]=>
  int(10)
}

如果您希望type1Type1是相同的密钥(不区分大小写),您可以执行以下操作:

foreach($info as $elem) {
    $counts[strtolower($elem['name1'])] += $elem['count'];
}

输出:

Warning: Undefined array key "type1"
Warning: Undefined array key "type2"
array(2) {
  ["type1"]=>
  int(44)
  ["type2"]=>
  int(21)
}