foreach for php合并并在php中添加总金额

时间:2016-09-13 16:17:40

标签: php codeigniter

所以我这里有一个PHP代码:

    <?php foreach($posts as $post){ ?>
    <?php $totamount = ($post->price) * ($post->qty); ?>
    <table>
        <tr>
            <th>Item Name</th>
            <th>Quantity</th>
            <th>Price<th>
            <th>Total</th>
        </tr>
        <tr>
            <td><div class="name"><?php echo $post->name; ?></div></td>
            <td><div class="qty"><?php echo $post->qty; ?></div></td>
            <td><div class="price"><?php echo $post->price; ?></div></td>
            <td><div class="totamount"><?php echo $totamount; ?></div></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
    <div class="client"><?php echo $post->firstname; ?> <?php echo $post->lastname; ?></div>
<?php } ?>

如果客户保留一种产品是好的,但当客户添加新产品时,收据将如下所示:

    Item Name    Quantity    Price   Total
     gown           2        7.50     15

    clients name

    Item Name    Quantity    Price   Total
    bridal          1        5.00      5

    clients name

突然间,这成了一个循环,你可以看到<th>正在循环,还有客户名称,我希望它是这样的:

    Item Name    Quantity    Price   Total
     gown           2        7.50     15
    bridal          1        5.00      5

                       TOTAL AMOUNT:  20

    clients name

而且,如何在不使用SQL的情况下获得TOTAL AMOUNT,因为Total不在数据库中!我将如何做正确的事?

1 个答案:

答案 0 :(得分:0)

仅使用产品信息

<tr>放入循环中
<table>
    <tr>
        <th>Item Name</th>
        <th>Quantity</th>
        <th>Price<th>
        <th>Total</th>
    </tr>
    <?php foreach($posts as $post){ ?>
        <?php $totamount = ($post->price) * ($post->qty); 
        $orderTotal += $totamount;
    ?>
        <tr>
            <td><div class="name"><?php echo $post->name; ?></div></td>
            <td><div class="qty"><?php echo $post->qty; ?></div></td>
            <td><div class="price"><?php echo $post->price; ?></div></td>
            <td><div class="totamount"><?php echo $totamount; ?></div></td>
        </tr>
    <?php } ?>
</table>
<div class="total"><?=$orderTotal?></div>
<div class="client"><?php echo $post->firstname; ?> <?php echo $post->lastname; ?></div>