How can I sum objects property of an array using PHP

后端 未结 3 1958
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 16:45

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.

相关标签:
3条回答
  • 2021-01-06 17:26

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

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

    0 讨论(0)
  • 2021-01-06 17:38
    $sum = 0;
    $result=$res->intervalStats;
    foreach($result as $key=>$value){
    
    if(isset($value->spent))   
        $sum += $value->spent;
    }
    echo $sum;
    
    0 讨论(0)
  • 2021-01-06 17:40

    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
    
    0 讨论(0)
提交回复
热议问题