欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多维数组遍历,购物车总金额实例

程序员文章站 2022-04-17 18:47:03
...

php 多维数组遍历

  • 多维数组涉及循环嵌套
  • for 循环遍历索引数组还行
  • foreach 遍历数组专用
  1. <?php
  2. $arr = [
  3. ['001', 'hoang', 'HR', 'salary'],
  4. ['002', 'ha', 'HR', 'tdung']
  5. ];
  6. // for 循环遍历二维数组
  7. for ($i = 0; $i <= count($arr); $i++) {
  8. for ($j = 0; $j <= count($arr[$i]); $j++) {
  9. echo $arr[$i][$j];
  10. echo '<br>';
  11. }
  12. }
  13. $arr = [
  14. ['id' => '001', 'name' => 'hoang', 'dep' => 'HR', 'work' => 'salary'],
  15. ['id' => '002', 'name' => 'ha', 'dep' => 'HR', 'work' => 'tdung']
  16. ];
  17. foreach ($arr as $results) {
  18. foreach ($results as $key => $res) {
  19. echo $key . '--' . $res;
  20. echo '<hr>';
  21. }
  22. }

[http://help10086.cn/0118/demo2.php]

购物车商品总结的计算

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>购物车求和</title>
  8. </head>
  9. <body>
  10. <?php
  11. $arr = [
  12. ['id' =>
  13. '1', 'name' => 'iphone10', 'num' => 1, 'price' => 8000], ['id' => '2',
  14. 'name' => 'iphone11', 'num' => 2, 'price' => 10000], ['id' => '3', 'name' =>
  15. 'iphone12', 'num' => 4, 'price' => 12000], ['id' => '4', 'name' =>
  16. 'iphone13', 'num' => 2, 'price' => 11000], ]; function getvalSum($arr) {
  17. foreach ($arr as $goods) { foreach ($goods as $val) { // print_r($val);
  18. $total = $goods['num'] * $goods['price']; $valSam += $total; }; }; echo
  19. $valSam; } ?>
  20. <h2>购物车求和</h2>
  21. <table border="1" width="480px" cellspacing="0" style="text-align:center;">
  22. <thead style="background-color: #f50303;height: 40px;font-size: 18px;">
  23. <tr>
  24. <td>id</td>
  25. <td>品名</td>
  26. <td>数量</td>
  27. <td>单价</td>
  28. <td>小计</td>
  29. </tr>
  30. </thead>
  31. <tbody>
  32. <?php foreach ($arr as $value) : ?>
  33. <tr>
  34. <td><?php echo $value['id'] ?></td>
  35. <td><?php echo $value['name'] ?></td>
  36. <td><?php echo $value['num'] ?></td>
  37. <td><?php echo $value['price'] ?></td>
  38. <td><?php echo $value['num'] * $value['price'] ?></td>
  39. </tr>
  40. <?php endforeach; ?>
  41. <tr style="background-color: yellow;">
  42. <td colspan="4">总计</td>
  43. <!-- <td>1</td> -->
  44. <!-- <td>1</td> -->
  45. <!-- <td>1</td> -->
  46. <td><?php getvalSum($arr) ?></td>
  47. </tr>
  48. </tbody>
  49. </table>
  50. </body>
  51. </html>

[http://help10086.cn/0118/demo3.php]