0

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?

4

2 に答える 2

2

You can just reference 'totalPrice' directly:

$finalTotal = 0;
foreach($cart as $value) {
    $finalTotal += $value['totalPrice'];
}
于 2010-09-17T16:13:51.133 に答える
1

You can access the elements directly using the indexes:

$finalTotal = 0.00;
foreach($cart as $value)
    $finalTotal = $finalTotal + $value['totalPrice'];
于 2010-09-17T16:13:20.373 に答える