如何使用PHP对数组的对象属性求和

问题描述 投票:2回答:3

我有一个对象数组,我想要对其中一个属性的值求和。这是一张将显示数组结构的图片。

这是我的代码,但不起作用。

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;
php arrays arrayobject
3个回答
3
投票
$sum = 0;
$result=$res->intervalStats;
foreach($result as $key=>$value){

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

6
投票

利用下面的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

0
投票

这适用于lates PHP版本(在7.2上测试)

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

© www.soinside.com 2019 - 2024. All rights reserved.