PHP Foreach从数据库循环计算总和 [英] PHP Foreach loop from database to calculate sum
问题描述
我想知道的是,对于所有经验丰富的编码人员,我将如何从我的数据库中获取一个值,该值存储为double值
I am wondering for all of you more experienced coders how I would take a value coming from my database, which is stored as a double
(常规时间和加班时间变量)
(Variables regulartime and overtime)
然后计算两列中每列的总和.
And then calculate the sum of each of the two columns..
foreach ($result as $row) {
echo '<tr><td>' . $row['username'] . '</td>
<td>' . $row['date'] . '</td>
<td>' . $row['jobnumber'] . '</td>
<td>' . $row['customer'] . '</td>
<td>' . $row['worksite'] . '</td>
<td>' . $row['duties'] . '</td>
<td>' . $row['regulartime'] . '</td>
<td>' . $row['overtime'] . '</td></tr>';
}
非常感谢您的帮助.
泰勒
编辑 我想在两者的底部添加最后一行以显示总和
EDIT I want to add a final row at the bottom of the two to display the sums
推荐答案
要显示包含每一行的表,然后显示包含总和的最后一行,则只需使用现有的foreach
循环来递增总计:
As you want to display a table containing each row, then a final row containing the sum, you only have to use your existing foreach
loop to increment the totals :
$totalRegularTime = 0;
$totalOverTime = 0;
foreach ($result as $row) {
echo '<tr><td>' . $row['username'] . '</td>
<td>' . $row['date'] . '</td>
<td>' . $row['jobnumber'] . '</td>
<td>' . $row['customer'] . '</td>
<td>' . $row['worksite'] . '</td>
<td>' . $row['duties'] . '</td>
<td>' . $row['regulartime'] . '</td>
<td>' . $row['overtime'] . '</td></tr>';
$totalRegularTime += $row['regulartime'];
$totalOverTime += $row['overtime'];
}
echo '<tr><td colspan="6">TOTAL</td>
<td>' . $totalRegularTime . '</td>
<td>' . $totalOverTime . '</td></tr>';
但是,如果您不需要首先显示table
中的所有行,最好的解决方案是使用SQL获取总和.
如果您不能使用SQL(例如,您的数据不是来自数据库),则 Eternal1 的答案是一个很好的选择.而且很干净.
However if you didn't need to display all the rows in a table
first, the best solution would have been to get the sums using SQL.
Eternal1's answer is a good alternative if you can't use SQL (if your data doesn't come from database for example). And it's pretty clean.
这篇关于PHP Foreach从数据库循环计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!