2015-04-07 107 views
-1
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)。聯合陣列的結果的總和

回答

1

通過與foreach陣列時,您環路,並把no_of_participants在一個變量$sum

$sum = 0; 
foreach($array as $object){ 
    $sum = $sum + $object->no_of_participants; 
} 

echo $sum; //Returns 3 
1

試試這個:

$sum = 0; 
foreach($datas as $data){ 
    $sum += $data->no_of_participants; 
} 

echo $sum; 
0

假設你在你的問題中定義的$對象:

然後按照下列步驟操作:

$array = json_decode(json_encode($object), true); 
$sum = 0; 
foreach($array as $val){ 
    $sum = $sum + $val->no_of_participants; 
} 
echo $sum; 
0
$sum = array_reduce(
    $myArrayOfObjects, 
    function($runningTotal, $record) { 
     $runningTotal += $record->no_of_participants; 
     return $runningTotal; 
    } 
);