使用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