How can I sum objects property of an array using PHP

Mr Alb picture Mr Alb · Jun 9, 2015 · Viewed 9.3k times · Source

I have an array of objects, and i want to sum value of one of the property.Here is a picture which will show the structre of array.enter image description here

Here is my code,that doesn't work.

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;

Answer

Akshay Hegde picture Akshay Hegde · Jun 9, 2015

Make use of array_reduce function like below

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

Sample Test

 [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;
 ?>

Output

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

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

         )

 )

 6