Как я могу суммировать свойства объектов массива с помощью PHP


У меня есть массив объектов, и я хочу суммировать значение одного из свойств.Вот картинка, на которой будет показана структура массива.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;
Author: Akshay Hegde, 2015-06-09

3 answers

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

if(isset($value->spent))   
    $sum += $value->spent;
}
echo $sum;
 3
Author: Babar, 2015-06-09 08:18:48

Используйте функцию 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
 6
Author: Akshay Hegde, 2015-06-09 08:28:50

Это работает на последних версиях PHP (протестировано на 7.2)

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

 0
Author: Tony, 2018-03-03 13:39:37