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

Mr *_*Alb 2 php arrays arrayobject

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

这是我的代码,但不起作用.

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;
Run Code Online (Sandbox Code Playgroud)

Aks*_*gde 7

使用如下所示的array_reduce函数

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

样品测试

 [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;
 ?>
Run Code Online (Sandbox Code Playgroud)

产量

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

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

         )

 )

 6
Run Code Online (Sandbox Code Playgroud)


Bab*_*bar 5

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

if(isset($value->spent))   
    $sum += $value->spent;
}
echo $sum;
Run Code Online (Sandbox Code Playgroud)