如何在 php 中从数组构建的 table 中插入分隔符?

How to insert separator in table built from array in php?

您好,我有这个 table 从数组构建的,但我想在每个描述组下插入一行并添加数量,但我不知道该怎么做。

table 是使用此代码通过 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 } ?>

我会这样做:

    // Group first your array into a multilevel array, I'm using the description as main key.
    $newArr = [];
    foreach($resulta as $val) {
        $newArr[$val['des']] = $val;
    }

    // parse the array accordingly
    foreach ($newArr as $res) {
        foreach($res as $r) { ?>
        <tr>
            <th><?php echo $r['des'] ?></th>
            <th><?php echo $r['name'] ?></th>
            <th><?php echo $r['slug'] ?></th>
            <th><?php echo $r['details'] ?></th>
            <th><?php echo $r['price'] ?></th>
        </tr>
    <?php } ?>
    <tr>
        <th colspan="5"><?php echo "This is your separator"; ?></th>
    </tr>
    }

其中一种方式:

使用一个临时变量,假设 $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>