Question

I have got an array that looks like:

$costs = 
  Array
   (
    [0] => Array
       (
        [amount_set] => 27.99
        [amount_cost] => 17
        [amount_markup] => 3.6

    )

  )

  Array
      (
       [0] => Array
         (
        [amount_set] => 6.99
        [amount_cost] => 3.12
        [amount_markup] => 1          
       )

       [1] => Array
        (           
          [amount_set] => 16.99
          [amount_cost] => 10
          [amount_markup] => 2.54         
        )
)

What I'm looking to do is loop through the $cost array and for each one calculate a total value of amount_set.

If I use:

foreach($costs as $cost) {
   $amount +=$cost['amount_set'];
}

Then I will get the total of all combined amount_set values, but I just want to get the total of each individual one. For example my first total will be 27.99 and the second one should be 23.98. How would I go about doing this?

Was it helpful?

Solution

If I understand you correctly, $costs is an array of cost sets, which are arrays of costs, and you want the totals for each set. That would mean you need something like:

foreach($costs as $cost_set) {
    $amount = 0;
    foreach ($cost_set as $cost) {
        $amount += $cost['amount_set'];
    }
    $amounts[] = $amount;
}

That will give yo an array of subtotals based on the groups of costs.

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