php,如何计算while循环的总和?

时间:2011-08-15 22:58:54

标签: 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 + ...

任何想法?

感谢

3 个答案:

答案 0 :(得分:6)

要么创建一个单独的变量并在while书中执行总和($var += $get_keywords3['grand_total'];),要么在查询中进行求和,如果您只想求和(SELECT SUM(grand_total) -- etc)。

答案 1 :(得分: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.

这个离开了。

答案 2 :(得分: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/>";