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

7

我有一个对象数组,想要对其中一个属性的值进行求和。下面的图片展示了这个数组的结构: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;

你需要循环遍历 $res->intervalStats - Rikesh
->sent?也许你的意思是->spent。 - Kevin
@ghost 对不起,它已经花费完了...顺便说一下,对我不起作用。 - Mr Alb
3个回答

13

可以像下面这样使用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

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

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

1
这适用于最新的PHP版本(在7.2上测试过)。 $sum = array_sum(array_column($res->intervalStats, 'spent'));

2
如果子元素是数组类型,那么这会起作用...但现在它的类型是对象。 - Mahmoud Abdelsattar
@MahmoudAbdelsattar,如果属性是公共的,它仍然可以工作,这似乎是这样的。 - Turab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接