如何使用 PHP 对数组的对象 属性 求和
How can I sum objects property of an array using PHP
我有一个对象数组,我想对其中一个的值求和 property.Here 是一张显示数组结构的图片。
这是我的代码,它不起作用。
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;
$sum = 0;
$result=$res->intervalStats;
foreach($result as $key=>$value){
if(isset($value->spent))
$sum += $value->spent;
}
echo $sum;
像下面那样使用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
这适用于最新的 PHP 版本(在 7.2 上测试)
$sum = array_sum(array_column($res->intervalStats, 'spent'));
我有一个对象数组,我想对其中一个的值求和 property.Here 是一张显示数组结构的图片。
这是我的代码,它不起作用。
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;
$sum = 0;
$result=$res->intervalStats;
foreach($result as $key=>$value){
if(isset($value->spent))
$sum += $value->spent;
}
echo $sum;
像下面那样使用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
这适用于最新的 PHP 版本(在 7.2 上测试)
$sum = array_sum(array_column($res->intervalStats, 'spent'));