我正在学习PHP中的数组,并想知道如何在多维数组中提取和计算项目,以便进行小额收据练习:
$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)
);
我的麻烦在于找出如何单独列出项目以便打印或计算(例如,将项目乘以销售税),以显示为收据。我知道我的HTML和CSS,我知道如何在PHP中进行基本计算,但是通过多维数组循环让我陷入困境。非常感谢您的任何提示。
答案 0 :(得分:3)
PHP有一个foreach
语句,可用于迭代数组。它也适用于嵌套的:
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
答案 1 :(得分:1)
<?php
$subtotal = 0;
$tax = 0;
foreach ($products as $product){
$subtotal += $product['price'];
$tax += $product['tax'];
}
$grandtotal = $subtotal + $tax;