如何遍历多维数组并添加键值并进行最终计算

时间:2014-03-03 20:50:42

标签: php arrays codeigniter multidimensional-array

在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”]相加,然后打印最终计算一次?

2 个答案:

答案 0 :(得分:2)

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

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

$total = 0;

foreach ($result as $item){

     $total = $total + $item['charge_amt'];

}

echo $total;

答案 1 :(得分:1)

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

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

无论如何,由于这看起来像数据库查询的结果,为什么不让数据库直接总结总量?