douzha6055 2019-07-24 15:47
浏览 36

如何根据键合并数组并总结值?

I have an array something like below. I want to merge the nested array and display the totals. Here ID = 60.I want to merge this [0] and [1] depending in the ID value i.e., 60.

Array(
    [0] => Array
    (
        [ID] => 60
        [TOTAL] => 500
    )
    [1] => Array
    (
        [ID] => 60
        [TOTAL] => 600
    )
   [2] => Array
    (
        [ID] => 61
        [TOTAL] => 600
    )

   )

I tried with two for loops

foreach($result as $key=>$value){
    foreach($result as $key1 => $value1){
    // Do stuffs here
    }
}

I want the output as

Array(
     [0] => Array(
           [ID] =>60
           [TOTAL] => 1100
     )
     [1] =>Array(
           [ID] =>61
           [TOTAL] => 600
     )
  )
  • 写回答

3条回答 默认 最新

  • dongnaigu2052 2019-07-24 16:05
    关注
    <?php
    
    $result = Array(
         Array
        (
            'ID' => 60,
            'TOTAL' => 500
        ),
        Array
        (
            'ID' => 60,
            'TOTAL' => 600
        ),
       Array
        (
            'ID' => 61,
            'TOTAL' => 600
        )
       );
    
    $set = [];   
    
    
    foreach($result as $data){
        if(!isset($set[$data['ID']])) $set[$data['ID']] = 0;
        $set[$data['ID']] += $data['TOTAL'];
    }
    
    $result_set = [];
    
    foreach($set as $id => $total){
        $result_set[] = [
            'ID' => $id,
            'TOTAL' => $total
        ];
    }
    
    print_r($result_set);
    

    Demo: https://3v4l.org/NMmHC

    • We store IDs as keys in our $set array and keep adding the total to it whenever we come across the same key in the foreach loop.
    • In the end, we collect the results in a new array with ID and it's respective total.
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line