2014-01-08 73 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; 
?> 

希望有所幫助。

問候, 拉爾夫