Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 初学者数组问题,从2D数组中提取要列出和操作的项_Php - Fatal编程技术网

Php 初学者数组问题,从2D数组中提取要列出和操作的项

Php 初学者数组问题,从2D数组中提取要列出和操作的项,php,Php,我正在学习PHP中的数组,并想知道如何在多维数组中提取和计算项目,对于我正在尝试的小收据练习: $products = array('Textbook' => array('price' => 35.99, 'tax' => 0.08), 'Notebook' => array('price' => 5.99, 'tax' => 0.08), 'Snack' => a

我正在学习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中进行基本的计算,但通过多维数组循环让我陷入困境。非常感谢你给我的建议

PHP有一个
foreach
语句,用于在数组上迭代。它同样适用于嵌套对象:

<?php

$subtotal = 0;
$tax = 0;

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

$grandtotal = $subtotal + $tax;
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

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