douya5331 2015-04-12 14:48
浏览 39
已采纳

按字段分组数组并给出总值

I'm trying to group the following array by 'label' to give a total value for each person.

Array
(
 [0] => Array
    (
        [label] => John
        [value] => 84
    )

 [1] => Array
    (
        [label] => Darren
        [value] => 28
    )

 [2] => Array
    (
        [label] => John
        [value] => 20
    )

 [3] => Array
    (
        [label] => Morgan
        [value] => 20
    )

 [4] => Array
    (
        [label] => Hannah
        [value] => 14
    )

 [5] => Array
    (
        [label] => Morgan
        [value] => 14
    )

 [6] => Array
    (
        [label] => Darren
        [value] => 10
    )
)

This would be the end result:

Array
(
 [0] => Array
    (
        [label] => John
        [value] => 104
    )

 [1] => Array
    (
        [label] => Darren
        [value] => 38
    )

 [2] => Array
    (
        [label] => Morgan
        [value] => 34
    )

 [3] => Array
    (
        [label] => Hannah
        [value] => 14
    )
)

I'm assuming I need to use foreach to group the labels together but I'm stuck for the best way to do this.

  • 写回答

2条回答 默认 最新

  • duanlu0559 2015-04-12 15:00
    关注

    I would do something like this (expecting your array in $array):

    // output array
    $newArray = array();
    
    // loop over the input array
    foreach($array as $entry) {
        // loop over the output array
        foreach($newArray as &$currentEntry) {
            // check if there is a the current label
            if($currentEntry['label'] == $entry['label']) {
                // if so, add the value and continue (also parent)
                $currentEntry['value'] += $entry['value'];
                continue 2;
            }
        }
        // if the current label wan't found, it will get here and add an entry
        array_push($newArray,$entry);
    }
    
    print_r($newArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算