6

我有一个对象数组,我想对其中一个属性的值求和。这是一张显示数组结构的图片。在此处输入图像描述

这是我的代码,它不起作用

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;
4

3 回答 3

11

使用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
于 2015-06-09T08:23:28.923 回答
5
$sum = 0;
$result=$res->intervalStats;
foreach($result as $key=>$value){

if(isset($value->spent))   
    $sum += $value->spent;
}
echo $sum;
于 2015-06-09T08:18:48.623 回答
1

这适用于最新的 PHP 版本(在 7.2 上测试)

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

于 2018-03-03T13:39:37.387 回答