douwen5690 2009-10-13 21:20
浏览 33
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • dowm41315 2009-10-13 21:27
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站