欢迎光临
我们一直在努力

php计算二维数组中某一项之和的方法

数组示例:

  [0] => array(3) {     ["id"] => string(1 "1"     [""] => string(4) "jhon"     ["amount"] => string(3) "850"    }  [1] => array(3) {     ["id"] => string(1) "2"     [""] => string(5) "david"     ["amount"] => string(4) "1200"    }  [2] => array(3) {     ["id"] => string(1) "3"     [""] => string(4) "lucy"     ["amount"] => string(3) "200"    }

需求说明:计算数组中所有元素的amount项的和。

方法一:

  $total = array_sum(array_map(function($val){return $val['amount'];}, $arr));

方法二:

  $total = 0;  foreach($arr as $item){      $total += (int) $item['amount'];  }
赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《php计算二维数组中某一项之和的方法》
文章链接:https://www.ruiwuer.com/408.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

登录

找回密码

注册