dongluanban3536 2018-05-31 10:41
浏览 186
已采纳

如何计算PHP中相同数组值的总和

I have an array like this

$estimate[0]=>
'gear' =>'MMG'
'total' =>  315
   'efforts' => 9
   'afh' => 18

$estimate[1]=>
    'gear' =>'MMG'
    'total' =>  400
       'efforts' => 2
       'afh' => 6

$estimate[2]=>
    'gear' =>'BOO'
    'total' =>  200
       'efforts' => 20
       'afh' => 16

$estimate[3]=>
    'gear' =>'BOB'
    'total' =>  250
       'efforts' => 20
       'afh' => 16

I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.

$calculate = array();   
for($et=0;$et<count($estimate);):   
if($et==0):
    $calculate[$et]['gear'] = $estimate[$et]['gear'];
    $calculate[$et]['total'] = $estimate[$et]['total'];
    $calculate[$et]['efforts'] = $estimate[$et]['efforts'];
    $calculate[$et]['afh'] = $estimate[$et]['afh'];                 
    goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
    if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
        $calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
        $calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
        $calculate[$cet]['afh']    = $calculate[$cet]['afh'] + $estimate[$et]['afh'];                       
        goto loopend;   
    endif;
endfor;
    $calculate[$et]['gear'] = $estimate[$et]['gear'];
    $calculate[$et]['total'] = $estimate[$et]['total'];
    $calculate[$et]['efforts'] = $estimate[$et]['efforts'];
    $calculate[$et]['afh'] = $estimate[$et]['afh'];                 
    goto loopend;
loopend:$et++;  
endfor; 

The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.

  • 写回答

3条回答 默认 最新

  • drmcm84800 2018-05-31 12:12
    关注

    You might use array_reduce:

    $result = array_reduce($estimate, function($carry, $item) {
        if (!isset($carry[$item["gear"]])) {
            $carry[$item["gear"]] = $item;
            return $carry;
        }
    
        $carry[$item["gear"]]["total"] += $item["total"];
        $carry[$item["gear"]]["efforts"] += $item["efforts"];
        $carry[$item["gear"]]["afh"] += $item["afh"];
    
        return $carry;
    });
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用