2014-01-08 51 views
0

我有以下的PHP/HTML代码:从一个foreach生成的表计算总的价格在PHP

<div id="demo"> 
    <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> 
     <thead> 
      <tr> 
       <th>Medicine Name</th> 
       <th>Batch Number</th> 
       <th>Total Quantity</th> 
       <th>Expiry Date(s)</th> 
       <th>Selling Price</th> 
       <th> Total Price</th> 
       <th>Issue</th> 
      </tr> 
     </thead> 

     <tbody> 
<?php foreach ($prescription as $prescribed): ?> 
       <tr class="odd gradeX"> 
        <td><?php echo $prescribed['commodity_name']; ?></td> 
        <td ><?php echo $prescribed['batch_no']; ?></td> 
        <td><?php echo $prescribed['total_quantity']; ?></td> 
        <td><?php echo $prescribed['expiry_date']; ?></td> 
        <td ><?php echo $prescribed['selling_price']; ?></td> 
        <td><?php 

        $total_quantity = $prescribed['total_quantity']; 
        $selling_price = $prescribed['selling_price']; 
        $total_quantity_float = floatval($total_quantity); 
        $selling_price_float = floatval($selling_price); 
        $total_price = $total_quantity_float*$selling_price_float; 
        echo $total_price; 

        ?></td> 
        <td> 
         <a class="issue" href="#types" id="issue">Issue</a> 
         <input type="hidden" name="batch_no" id="batch_no" value="<?php echo $prescribed['batch_no']; ?>"/> 
        </td> 
    <!--      <td> <a id="issue1" class="issue1" href="#types">Issue</a> </td>--> 
       </tr> 
<?php endforeach; ?> 
     </tbody> 
    </table> 

</div> 

我想获得其上显示(TOTAL_PRICE变量)TOTAL_PRICE变量的总和为桌子上一排。这应该显示所有商品的总价格,我怎样才能做到最好?

+0

你的意思是客户端或服务器端? – Lexib0y

回答

1

试试这个

<?php 
$total_price_sum = 0; 
foreach ($prescription as $prescribed){ 
    .. 
    .. 
    $total_price_sum = $total_price_sum + $total_price; 
} 
echo $total_price_sum; 

?>

2

您可以通过每次循环时添加一个变量来实现。这可以做到如下:

<?php 
$grand_total = 0; 
foreach ($prescription as $prescribed){ 
    ?> 
    ..... all the HTML bits ..... 
    <? 
    $grand_total = $grand_total + $total_price; 
} 
echo $grand_total; 
?> 

希望有所帮助。

问候, 拉尔夫