按一列对多维数组进行分组并对另一列求和

问题描述 投票:0回答:3

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

数组格式如下:

$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]
php arrays multidimensional-array sum grouping
3个回答
0
投票
$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
)

0
投票

这是我的看法。

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;

0
投票

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

$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)
}

如果你想让

type1
Type1
是同一个键(不区分大小写),你可以这样做:

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.