Beginner array problem, extracting items from a 2D array to list and manipulate

I am learning arrays in PHP and would like to know how to do something like extracting and calculating items in a multidimensional array, for a small receipt exercise I am attempting:

$products = array('Textbook' =>  array('price' => 35.99, 'tax' => 0.08), 
                  'Notebook' =>  array('price' => 5.99,  'tax' => 0.08),
                  'Snack'    =>  array('price' => 0.99,  'tax' => 0) 
                 );

My trouble is finding out how to list the items separately in order to print or calculate (for example, multiplying an item by it's sales tax), to display as a receipt. I know my HTML and CSS, I know how to do basic calculations within PHP, but looping through a multidimensional array has gotten me stuck. Thank you very much for any tips.

0 php
13.10.2009 21:20:24
2 ОТВЕТА
РЕШЕНИЕ

PHP has a foreach statement that's useful for iterating over arrays. It works just as well for nested ones:

foreach($products as $name => $product)
    foreach($product as $fieldName => $fieldValue)
        // $products is the whole array
        // $product takes the value of each array in $products, one at a time
        // e.g. array('price' => 35.99, 'tax' => 0.08)
        // $name takes the value of the array key that maps to that value
        // e.g. 'Textbook'
        // $fieldName takes the name of each item in the sub array
        // e.g. 'price' or 'tax'
        // $fieldValue takes the value of each item in the sub array
        // e.g. 35.99 or 0.08
3
13.10.2009 21:27:47
<?php

$subtotal = 0;
$tax = 0;

foreach ($products as $product){
    $subtotal += $product['price'];
    $tax += $product['tax'];
}

$grandtotal = $subtotal + $tax;
1
13.10.2009 21:26:29