【问题标题】:How can I sum objects property of an array using PHP如何使用 PHP 对数组的对象属性求和
【发布时间】:2015-06-09 08:16:25
【问题描述】:

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

这是我的代码,不起作用

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;

【问题讨论】:

  • 你需要循环$res->intervalStats
  • ->sent?也许你的意思是->spent
  • @ghost 对不起它的花费...顺便说一句...对我不起作用

标签: php arrays arrayobject


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    $sum = 0;
    $result=$res->intervalStats;
    foreach($result as $key=>$value){
    
    if(isset($value->spent))   
        $sum += $value->spent;
    }
    echo $sum;
    

    【讨论】:

      【解决方案3】:

      这适用于最新的 PHP 版本(在 7.2 上测试)

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

      【讨论】:

      • 如果孩子是数组类型,这将起作用..这里是对象类型。
      猜你喜欢
      • 2020-10-14
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多