关联数组的结果总和

时间:2015-04-07 10:14:42

标签: php codeigniter

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)。

4 个答案:

答案 0 :(得分:1)

使用foreach循环遍历数组,并将no_of_participants放入变量$sum

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

echo $sum; //Returns 3

答案 1 :(得分:1)

试试这个:

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

echo $sum;

答案 2 :(得分:0)

假设您的问题中定义了$ object:

然后按照以下步骤操作:

$array = json_decode(json_encode($object), true);
$sum = 0;
foreach($array as $val){
    $sum = $sum + $val->no_of_participants;
}
echo $sum;

答案 3 :(得分:0)

$sum = array_reduce(
    $myArrayOfObjects,
    function($runningTotal, $record) {
        $runningTotal += $record->no_of_participants;
        return $runningTotal;
    }
);