views:

30

answers:

2

I have a function that adds shopping cart data to an array of arrays. The array looks like this:

Array ( 
[0] => Array ( [TypeFlag] => S [qty] => 2 [denom] => 50 [certMessage] => [totalPrice] =>  100 )
[1] => Array ( [TypeFlag] => S [qty] => 1 [denom] => 25 [certMessage] => [totalPrice] => 25 ) 
) 

What I need to do is get the total price of all items in the cart- in this case, 125. How do I go about doing this? I know how to access specific values of an array, but how do I get the values from multiple arrays like this? I can print out each value in a loop, like this:

$finalTotal = 0.00;
foreach($cart as $value) {
        foreach($value as $key=>$item) {            
            error_log("cart  ".$key . ": ". $item);
        }
    }

Do I need to use an if inside the nested foreach and say if $key="totalPrice", add $item to $finalTotal? Or is there some other way to do it?

+1  A: 

You can access the elements directly using the indexes:

$finalTotal = 0.00;
foreach($cart as $value)
    $finalTotal = $finalTotal + $value['totalPrice'];
A. M.
+2  A: 

You can just reference 'totalPrice' directly:

$finalTotal = 0;
foreach($cart as $value) {
    $finalTotal += $value['totalPrice'];
}
rojoca
`$finalTotal += $value['totalPrice'] * $value['qty'];` considers the quantity.
hacksteak25
I think in the example `$value['totalPrice'] = $value['qty'] * $value['denom']`
rojoca
I don't need to take qty into account, the value of totalPrice in each array is already qty * unitPrice. I just needed to get the sum of totalPrice values for all the arrays, which the example does.
EmmyS