【问题标题】:Group multidimensional array by one column and sum the other column按一列对多维数组进行分组并对另一列求和
【发布时间】:2014-10-20 16:51:04
【问题描述】:

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

数组格式如下:

$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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的,先生。你的解决方案对我有帮助。请你帮助格式化 html 结构中的新数组,我正在发布我的 foreach 循环格式。我试图像这种类型 1-44 然后下一行type2-22(html格式)...请检查一次
    【解决方案2】:
    $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
    )
    

    【讨论】:

      【解决方案3】:

      这是我的看法。

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-21
        • 2018-05-22
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多