嗨,我有这个从数组构建的表,但我想在每个描述组下插入一行并添加数量,但我不知道该怎么做。
该表是使用此代码使用 foreach 构建的。
<?php
foreach ($resulta as $res) {
?>
<tr>
<th><?php echo $res['des'] ?></th>
<th><?php echo $res['name'] ?></th>
<th><?php echo $res['slug'] ?></th>
<th><?php echo $res['details'] ?></th>
<th><?php echo $res['price'] ?></th>
</tr><?php } ?>
方法之一:
使用临时变量,例如 $total 初始值 =0 ,然后将其递增 $res["price"]
然后如果 des 发生变化(或在 foreach 循环的末尾),则显示此变量并将其重置为 0
样本数据
<?php
$resulta[] = array("des"=>"samsung led tv", "name"=>'', "slug"=>'', $details=>'', "price"=>"8.99");
$resulta[] = array("des"=>"samsung led tv", "name"=>'', "slug"=>'', $details=>'', "price"=>"41.99");
$resulta[] = array("des"=>"samsung led tv", "name"=>'', "slug"=>'', $details=>'', "price"=>"144.99");
$resulta[] = array("des"=>"macbook pro", "name"=>'', "slug"=>'', $details=>'', "price"=>"2499.99");
$resulta[] = array("des"=>"macbook pro", "name"=>'', "slug"=>'', $details=>'', "price"=>"649.99");
$resulta[] = array("des"=>"macbook pro", "name"=>'', "slug"=>'', $details=>'', "price"=>"148.99");
$resulta[] = array("des"=>"dell vostro 3557", "name"=>'', "slug"=>'', $details=>'', "price"=>"1499.99");
?>
PHP 代码
<table border=1>
<?php
$initdesc="undefined"; $count=0; $total=0;
foreach ($resulta as $res) {
if ($initdesc !=$res["des"]) {
if ($count > 0) { ?>
<tr><td colspan=4 style="text-align:right;">Total<td><?php echo $total; ?>
<?php }
$total=0;
$initdesc=$res["des"];
}
?>
<tr>
<td><?php echo $res['des'] ?></td>
<td><?php echo $res['name'] ?></td>
<td><?php echo $res['slug'] ?></td>
<td><?php echo $res['details'] ?></td>
<td><?php echo $res['price'] ?></td>
</tr>
<?php
$count++;
$total=$total+$res['price'];
}
if ($count!=0) { ?>
<tr><td colspan=4 style="text-align:right;">Total<td><?php echo $total; ?>
<?php } ?>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句