7

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;
3
  • You need to loop around $res->intervalStats. Commented Jun 9, 2015 at 8:17
  • ->sent? maybe you meant ->spent Commented Jun 9, 2015 at 8:17
  • @ghost sorry its spent...bthway ...doesn't work for me Commented Jun 9, 2015 at 8:21

3 Answers 3

13

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
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

1

This is working on lates PHP versions (tested on 7.2)

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

2 Comments

This would work if the children are type of array .. here it is type of object.
@MahmoudAbdelsattar, it will still work if the properties are public, which seems to be so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.