Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum objects property of an array using PHP

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;
like image 651
Mr Alb Avatar asked Jun 09 '15 08:06

Mr Alb


People also ask

How do you sum values in array of objects?

To sum a property in an array of objects:Call the reduce() method to iterate over the array. On each iteration increment the sum with the specific value. The result will contain the sum of the values for the specific property.

Which function find sum of all the values in array in PHP?

The array_sum() function returns the sum of all the values in the array.

How Can Get object property value in PHP?

The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object.


3 Answers

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
like image 159
Akshay Hegde Avatar answered Nov 11 '22 09:11

Akshay Hegde


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

if(isset($value->spent))   
    $sum += $value->spent;
}
echo $sum;
like image 23
abh Avatar answered Nov 11 '22 10:11

abh


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

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

like image 33
Tony Avatar answered Nov 11 '22 09:11

Tony