数组示例:
[0] => array(3) {
["id"] => string(1 "1"
["name"] => string(4) "jhon"
["amount"] => string(3) "850"
}
[1] => array(3) {
["id"] => string(1) "2"
["name"] => string(5) "david"
["amount"] => string(4) "1200"
}
[2] => array(3) {
["id"] => string(1) "3"
["name"] => 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'];
}