Question

Working in CI, wanting to loop through a result_array and add values from an amount key value. The array is multidimensional

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
   }
}

How do I get it to loop through each array and add up each ["charge_amt"] and then print the final calculation once?

No correct solution

OTHER TIPS

Not sure if I am missing anything but it's just a foreach loop where $result represents the second layer of the array. So it's either

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

$total = 0;

foreach ($result as $item){

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

}

echo $total;

If you don't need the loop for anything else, this might be faster/shorter (PHP 5 >= 5.5.0):

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

Anyway, since this looks like a result from a database query, why don't you let the database sum up the total amount directly?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top