2009-10-13 7 views
0

J'apprends des tableaux en PHP et je voudrais savoir comment extraire et calculer des éléments dans un tableau multidimensionnel, pour un petit exercice de recette que j'essaie :Problème de tableau débutant, extraction d'éléments d'un tableau 2D pour lister et manipuler

$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) 
       ); 

Mon problème est de trouver comment lister les éléments séparément afin d'imprimer ou de calculer (par exemple, la multiplication d'un élément par celui-ci de la taxe de vente), pour afficher un reçu. Je connais mon HTML et CSS, je sais comment faire des calculs de base en PHP, mais boucler à travers un tableau multidimensionnel m'a bloqué. Merci beaucoup pour vos conseils.

Répondre

3

PHP a une déclaration foreach qui est utile pour itérer sur les tableaux. Il fonctionne aussi bien pour les imbriqués:

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 
+0

l'a obtenu. Merci! – supergalactic

1
<?php 

$subtotal = 0; 
$tax = 0; 

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

$grandtotal = $subtotal + $tax;