多维数组遍历,购物车总金额实例
程序员文章站
2022-04-17 18:47:03
...
php 多维数组遍历
- 多维数组涉及循环嵌套
- for 循环遍历索引数组还行
- foreach 遍历数组专用
<?php
$arr = [
['001', 'hoang', 'HR', 'salary'],
['002', 'ha', 'HR', 'tdung']
];
// for 循环遍历二维数组
for ($i = 0; $i <= count($arr); $i++) {
for ($j = 0; $j <= count($arr[$i]); $j++) {
echo $arr[$i][$j];
echo '<br>';
}
}
$arr = [
['id' => '001', 'name' => 'hoang', 'dep' => 'HR', 'work' => 'salary'],
['id' => '002', 'name' => 'ha', 'dep' => 'HR', 'work' => 'tdung']
];
foreach ($arr as $results) {
foreach ($results as $key => $res) {
echo $key . '--' . $res;
echo '<hr>';
}
}
[http://help10086.cn/0118/demo2.php]
购物车商品总结的计算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>购物车求和</title>
</head>
<body>
<?php
$arr = [
['id' =>
'1', 'name' => 'iphone10', 'num' => 1, 'price' => 8000], ['id' => '2',
'name' => 'iphone11', 'num' => 2, 'price' => 10000], ['id' => '3', 'name' =>
'iphone12', 'num' => 4, 'price' => 12000], ['id' => '4', 'name' =>
'iphone13', 'num' => 2, 'price' => 11000], ]; function getvalSum($arr) {
foreach ($arr as $goods) { foreach ($goods as $val) { // print_r($val);
$total = $goods['num'] * $goods['price']; $valSam += $total; }; }; echo
$valSam; } ?>
<h2>购物车求和</h2>
<table border="1" width="480px" cellspacing="0" style="text-align:center;">
<thead style="background-color: #f50303;height: 40px;font-size: 18px;">
<tr>
<td>id</td>
<td>品名</td>
<td>数量</td>
<td>单价</td>
<td>小计</td>
</tr>
</thead>
<tbody>
<?php foreach ($arr as $value) : ?>
<tr>
<td><?php echo $value['id'] ?></td>
<td><?php echo $value['name'] ?></td>
<td><?php echo $value['num'] ?></td>
<td><?php echo $value['price'] ?></td>
<td><?php echo $value['num'] * $value['price'] ?></td>
</tr>
<?php endforeach; ?>
<tr style="background-color: yellow;">
<td colspan="4">总计</td>
<!-- <td>1</td> -->
<!-- <td>1</td> -->
<!-- <td>1</td> -->
<td><?php getvalSum($arr) ?></td>
</tr>
</tbody>
</table>
</body>
</html>