如何使用PHP对数组的对象属性求和

时间:2015-06-09 08:16:25

标签: php arrays arrayobject

我有一个对象数组,我想对其中一个属性的值求和。这是一张将显示数组结构的图片。enter image description here

这是我的代码,不起作用

print_r($res);//this appear the structure of array,which i will show.   
$sum = 0;   
foreach($res as $key=>$value){ 
   if(isset($value->sent))   
        $sum += $value->sent;
   }   
echo $sum;

3 个答案:

答案 0 :(得分:6)

使用array_reduce功能,如下所示

$sum = array_reduce($res->intervalStats, function($i, $obj)
{
    return $i += $obj->spent;
});
echo $sum;

样本测试

 [akshay@localhost tmp]$ cat test.php
 <?php

 $res = (object)array( "intervalStats" => array( (object)array("spent"=>1),(object)array("spent"=>5) ) );


 $sum = array_reduce($res->intervalStats, function($i, $obj)
 {
     return $i += $obj->spent;
 });

 // Input
 print_r($res);

 // Output
 echo $sum;
 ?>

<强>输出

 [akshay@localhost tmp]$ php test.php
 stdClass Object
 (
     [intervalStats] => Array
         (
             [0] => stdClass Object
                 (
                     [spent] => 1
                 )

             [1] => stdClass Object
                 (
                     [spent] => 5
                 )

         )

 )

 6

答案 1 :(得分:3)

$sum = 0;
$result=$res->intervalStats;
foreach($result as $key=>$value){

if(isset($value->spent))   
    $sum += $value->spent;
}
echo $sum;

答案 2 :(得分:0)

这适用于lates PHP版本(在7.2上测试)

$sum = array_sum(array_column($res->intervalStats, 'spent'));