2011-08-15 92 views
0

我有一個while循環,返回一些值:php,如何計算while循環的總和?

while ($get_keywords3 = mysql_fetch_array($keywords2)){ 
?> 
<tr> 
<td><span style="margin: 0 3px;"><?php echo $get_keywords3['grand_total'];?></span></td> 
</tr> 

<?php } 

這個返回:

123 
234 
345 
456 
... 

我想要的是那些加在一起:123 + 234 + 345 + ...

什麼想法?

感謝

回答

6

要麼做一個獨立的變量,做在書的同時($var += $get_keywords3['grand_total'];)的總和或在您的查詢的總和,如果你只是想總結(SELECT SUM(grand_total) -- etc)。

3
$sum = 0; 
while ($get_keywords3 = mysql_fetch_array($keywords2)){ 
?> 
<tr> 
<td><span style="margin: 0 3px;"><?php echo $get_keywords3['grand_total'];?></span></td> 
</tr> 
<?php 
$sum += $get_keywords3['grand_total']; 
} 

echo $sum; //This will be your total after the adding. 

This outta do it。

0
//To get Project Data 
echo "<table>"; 
echo "<tr>"; 
echo "<th> Project Code </th> <th>Project Name</th> <th>Contract Amount </th> <th>Total Paid </th><th>Balance Amount </th>"; 
echo "</tr>"; 



while ($voucher_data = mysql_fetch_assoc($voucher_query)) { 
     $pid = $voucher_data['pid']; 
    $project_data = mysql_fetch_assoc(mysql_query("SELECT * FROM `projectinfo` WHERE `id`='$pid'")); 

echo "<tr>"; 
    echo "<td>".$project_data['project_code']."</td>"; 
    echo "<td>".$project_data['Project_name']."</td>"; 
    echo "<td> TK.".$opening_bl = $voucher_data['opening_balance']."</td>"; 
    echo "<td> TK.".$paid = $voucher_data['SUM(current_pay)']."</td>"; 
    echo "<td> TK.". $pabe = $opening_bl - $paid."</td>"; 
echo "</tr>"; 

?> 
</div> 
<?php 
@$sum_op += $opening_bl; 
@$sum_paid += $paid; 
@$sum_pabe += $pabe; 
} 

echo "<tr>"; 
    echo "<td>Total</td>"; 
    echo "<td></td>"; 
    echo "<td> TK.".$sum_op."</td>"; 
    echo "<td> TK.".$sum_paid."</td>"; 
    echo "<td> TK.". $pabe = $opening_bl - $sum_pabe."</td>"; 
echo "</tr>"; 
echo "</table>"; 

    echo "<br/>";