Thursday, 30 August 2018

How to make a loop in a multidimensional array and add key values ​​and the final calculation

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?

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;

0 comments:

Post a Comment