联合阵列的结果的总和
问题描述:
Array
(
[0] => stdClass Object
(
[id] => 1
[price] => 1.00
[session_price] => 1.00
[no_of_participants] => 1
[session_id] => 1
[coupon_id] => 0
[group_discount_id] => 0
[order_id] => 1
[created] => 2015-04-02 16:56:24
[modified] => 2015-04-02 16:56:24
)
[1] => stdClass Object
(
[id] => 2
[price] => 2.00
[session_price] => 2.00
[no_of_participants] => 2
[session_id] => 1
[coupon_id] => 1
[group_discount_id] => 1
[order_id] => 1
[created] => 2015-03-03 00:00:00
[modified] => 2015-03-03 00:00:00
)
)
从上面我想总计no_of_participants
(即1 + 2 = 3
)。联合阵列的结果的总和
答
通过与foreach
阵列时,您环路,并把no_of_participants
在一个变量$sum
$sum = 0;
foreach($array as $object){
$sum = $sum + $object->no_of_participants;
}
echo $sum; //Returns 3
答
试试这个:
$sum = 0;
foreach($datas as $data){
$sum += $data->no_of_participants;
}
echo $sum;
答
假设你在你的问题中定义的$对象:
然后按照下列步骤操作:
$array = json_decode(json_encode($object), true);
$sum = 0;
foreach($array as $val){
$sum = $sum + $val->no_of_participants;
}
echo $sum;
答
$sum = array_reduce(
$myArrayOfObjects,
function($runningTotal, $record) {
$runningTotal += $record->no_of_participants;
return $runningTotal;
}
);