doute3621 2019-05-20 10:54
浏览 50
已采纳

PHP多维数组求和并使其唯一[重复]

This question already has an answer here:

Following is my array. I need to add its Sum field according to each emp_firstname. Some has only one time coming, some coming two times. how can we sum the field and make the array unique?

Array
(
    [0] => Array
        (
            [emp_firstname] => Alistair
            [non_pm] => AMZ
            [sum] => 2
        )


    [1] => Array
        (
            [emp_firstname] => Shakkeer
            [non_pm] => SHK
            [sum] => 3
        )

    [2] => Array
        (
            [emp_firstname] => Waqas
            [non_pm] => WAS
            [sum] => 12
        )

    [3] => Array
        (
            [emp_firstname] => Zain
            [non_pm] => ZAI
            [sum] => 9
        )


    [4] => Array
        (
            [emp_firstname] => Shakkeer
            [gud_pmeditor] => SHK
            [sum] => 4
        )

    [5] => Array
        (
            [emp_firstname] => Zain
            [gud_pmeditor] => ZAI
            [sum] => 2
        )

)
</div>
  • 写回答

1条回答 默认 最新

  • dreamworld2007 2019-05-20 11:06
    关注

    You can get the desired result using this approach

    $res=[];
    foreach($arr as $val){
      if(array_key_exists($val['emp_firstname'], $res))
        $res[$val['emp_firstname']]['sum'] = ($res[$val['emp_firstname']]['sum'] + $val['sum']);
      else
        $res[$val['emp_firstname']] = $val;
    }
    

    Live Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程