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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化