foeach函数或for循环读取数组以及购物车结算应用
程序员文章站
2022-03-15 23:51:03
...
1、foreach函数遍历数组
<body>
<?php
$customer = [
['code'=>'001','customername'=>'第一公司','linkman'=>'张三'],
['code'=>'002','customername'=>'第二公司','linkman'=>'张四'],
['code'=>'003','customername'=>'第三公司','linkman'=>'张五'],
['code'=>'004','customername'=>'第四公司','linkman'=>'张六'],
['code'=>'005','customername'=>'第五公司','linkman'=>'张七'],
];
?>
<table>
<p style="text-align:center ">客户信息</p>
<tr>
<?php foreach($customer as $v){ ?>
<td><?php echo $v['code']; ?> </td>
<td><?php echo $v['customername']; ?> </td>
<td><?php echo $v['linkman']; ?> </td>
</tr>
<?php } ?>
</table>
</body>
2、for循环遍历数组
<body>
<?php
$customer = [
['code'=>'001','customername'=>'深圳第一公司','linkman'=>'张三'],
['code'=>'002','customername'=>'深圳第二公司','linkman'=>'张四'],
['code'=>'003','customername'=>'深圳第三公司','linkman'=>'张五'],
['code'=>'004','customername'=>'深圳第四公司','linkman'=>'张六'],
['code'=>'005','customername'=>'深圳第五公司','linkman'=>'张七'],
];
?>
<table>
<p style="text-align:center ">客户信息</p>
<tr>
<?php for($i=0;$i<count($customer);$i++ ) { ?>
<td><?php echo $customer[$i]['code']; ?> </td>
<td><?php echo $customer[$i]['customername']; ?> </td>
<td><?php echo $customer[$i]['linkman']; ?> </td>
</tr>
<?php } ?>
</table>
</body>
3、购物车计算
<body>
<?php
$arr = [
['code'=>'001','commodity'=>'苹果','quantity'=>1,'price'=>10],
['code'=>'002','commodity'=>'香蕉','quantity'=>2,'price'=>11],
['code'=>'003','commodity'=>'梨','quantity'=>3,'price'=>12],
];
?>
<?php
function gouwuche($arr){
$total = 0;
foreach($arr as $v){
$quantity=$v['quantity'];
$price=$v['price'];
$total = $quantity * $price + $total;
/*$total1 = $quantity * $price;
$total += $total1;*/
};
return "{$total}元";
}
?>
<table>
<p style="text-align:center ">购物车结算</p>
<tr>
<td>编号</td>
<td>名称</td>
<td>数量 </td>
<td>单价</td>
</tr>
<tr>
<?php for($i=0;$i<count($arr);$i++ ) { ?>
<td><?php echo $arr[$i]['code']; ?> </td>
<td><?php echo $arr[$i]['commodity']; ?> </td>
<td><?php echo $arr[$i]['quantity']; ?> </td>
<td><?php echo $arr[$i]['price']; ?> </td>
</tr>
<?php } ?>
<tr>
<td>总价</td>
<td colspan=3><?php
echo gouwuche($arr);
?></td>
</tr>
</table>
</body>