简体   繁体   English

SUM在while循环-PHP

[英]SUM in a while loop - php

I have a loop which extracts 2 numbers from a table and then calculates the total. 我有一个循环,该循环从表中提取2个数字,然后计算总数。

I want to find the final total (sum of all totals). 我想找到最终总数(所有总数的总和)。

Is there a way to not use the DB to calculate the SUM but do it within the loop. 有没有一种方法可以不使用DB来计算SUM,而是在循环内执行。

while($row = $result->fetch_assoc()) {

   $total= $row["num1"] + $row["num2"];

}

How do I do this? 我该怎么做呢?

This is wrong: 这是错误的:

while($row = $result->fetch_assoc()) {

   $total= $row["num1"] + $row["num2"];

   $total = $total + $total;

}
$total=0;
while($row = $result->fetch_assoc()) {

   $sum= $row["num1"] + $row["num2"];

   $total = $total + $sum;

}

Simply initialize your $total outside the while Loop to zero and then add to it like so: 只需将while循环之外的$total初始化为零,然后像这样添加到它:

<?php

    $total     = 0;

    while($row = $result->fetch_assoc()) {
       $total += ($row["num1"] + $row["num2"]);

    }

You can simply add to the overall total with each iteration of the loop: 您可以简单地将每次循环的总和添加到总数中:

<?php 
$total = 0;
while($row = $result->fetch_assoc()) {
   $total += $row['num1'] + $row['num2'];
}

Actually in php you are not even required to initialize the $total variable as shown, but it is considered good practice, since it raises the readability of the code. 实际上,在php中,您甚至不需要初始化所示的$total变量,但由于它提高了代码的可读性,因此被认为是一种好习惯。

Doing this on the level of a scripting language obviously is much less efficient than using the db engine itself to calculate the sum. 在脚本语言级别上执行此操作显然比使用db引擎本身计算总和效率低得多。 But I assume this is not a real works task, but some seminar homework or similar... 但是我认为这不是一项真正的工作,而是一些研讨会作业或类似的工作...

$total = 0;

while($row = $result->fetch_assoc()) {
   $total += $row["num1"] + $row["num2"];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM