tags:

views:

239

answers:

4

Suppose I have an array like this:

$products = array('Shoes' =>  array('price' => 49.99, 'shipping' => 5), 
                  'Shirt' =>  array('price' => 29.99, 'shipping' => 3),
                  'Socks'=>   array('price' => 2.99, 'shipping' => 0) 
                    );

I am having trouble traversing a multi-dimensional array and adding the elements. Are there any tips for a PHP beginner? Thank you.

+1  A: 
$price = 0;
foreach($products as $product) {
  $price += array_sum($product);
}

This has the advantage of being more readable than using array_map, but provides the same output.

tj111
A: 

array_sum: http://php.net/manual/en/function.array-sum.php

rough sketch of code:

$total = 0;
foreach($products as $item => $amount_array){
   $total += array_sum($amount_array);
}
easement
A: 

Something like this?

$products = array('Shoes' =>  array('price' => 49.99, 'shipping' => 5), 
               'Shirt' =>  array('price' => 29.99, 'shipping' => 3),
               'Socks'=>   array('price' => 2.99, 'shipping' => 0) 
                 );

$total = 0;
foreach($products as $product)
{
 $total += $product["price"];
}

echo $total;

What you have is a variable called $product in each loop. That variable has in the first round "Shoes" as the key and the array as the value. So you can call it just as you would a normal array.

Ólafur Waage
+1  A: 

If you want the total price of all products, including shipping, you can calculate it without an explicit loop using array_sum and array_map:

echo array_sum(array_map('array_sum', $products)); // prints 90.97

Note that array_map applies array_sum to each of the inner arrays, after which array_sum is finally applied to the result of this operation.

Stephan202