【问题标题】:How to loop through a multidimensional array and add key values and out the final calculation如何遍历多维数组并添加键值并得出最终计算
【发布时间】:2014-03-03 20:50:41
【问题描述】:

在 CI 中工作,想要遍历一个 result_array 并从一个数量键值中添加值。数组是多维的

array(2)
{
    [0]=> array(9)
    {       
        ["id"]=> string(1) "1"
        ["resident_id"]=> string(1) "1"
        ["charge_amt"]=> string(6) "250.00"
        ["charge_key"]=> string(3) "HOM"
        ["charge_desc"]=> string(25) "Homeowner Association Fee"
        ["charge_date"]=> string(19) "2014-03-04 03:08:08"
        ["active"]=> string(1) "1"
        ["created_at"]=> string(19) "2014-03-03 14:17:00"
        ["updated_at"]=> NULL
   }

   [1]=> array(9)
   {
        ["id"]=> string(1) "2"
        ["resident_id"]=> string(1) "1"
        ["charge_amt"]=> string(5) "25.00"
        ["charge_key"]=> string(3) "LAT"
        ["charge_desc"]=> string(8) "Late Fee"
        ["charge_date"]=> string(19) "2014-03-04 04:11:10"
        ["active"]=> string(1) "1"
        ["created_at"]=> string(19) "2014-03-03 04:10:09"
        ["updated_at"]=> NULL
   }
}

如何让它遍历每个数组并将每个 ["charge_amt"] 相加,然后打印一次最终计算?

【问题讨论】:

    标签: php arrays codeigniter multidimensional-array


    【解决方案1】:

    不确定我是否遗漏了任何东西,但它只是一个 foreach 循环,其中 $result 代表数组的第二层。所以要么是

    foreach($result as $item)foreach($array['result'] as $item)

    $total = 0;
    
    foreach ($result as $item){
    
         $total = $total + $item['charge_amt'];
    
    }
    
    echo $total;
    

    【讨论】:

      【解决方案2】:

      如果您不需要其他任何循环,这可能会更快/更短(PHP 5 >= 5.5.0):

      $charge_amts = array_column($result_array, 'charge_amt');
      $total_charge_amt = array_sum($charge_amts);
      print $total_charge_amt;
      

      反正这看起来像是数据库查询的结果,为什么不让数据库直接汇总总金额呢?

      【讨论】:

      • 看起来很酷,但似乎值得一提的是,array_column() 仅适用于 php 5.5 或更高版本...
      • 对!目的是告诉人们那个(新)函数的存在......非常方便,现在在我的代码中替换/减少了许多循环!
      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2019-08-22
      • 2021-08-11
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多