php 在 while 循环(范围)之外使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7337743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:31:26  来源:igfitidea点击:

Using a variable outside of the while loop (scope)

phploopsscopewhile-loop

提问by Ryan Ward

Small problem regarding scope in PHP, I can't seem to call the variable $report outside of the while loop. I have tried various things, including return. This doesn't work, the only two functions that work here are if I echothe variable $reportinside the loop, or if I printit. Which I do not want to do, although it solves the problem, but I don't want random gibberish on the user's screen.

关于 PHP 范围的小问题,我似乎无法在 while 循环之外调用变量 $report。我尝试了各种方法,包括return. 这是行不通的,这里唯一可以使用的两个函数是如果 I是循环内的echo变量$report,或者如果 I 是print它。我不想这样做,虽然它解决了问题,但我不希望用户屏幕上出现随机乱码。

I have been looking around for the last 15 or so minutes, and I haven't seen any problems quite like this one on here.

在过去的 15 分钟左右,我一直在四处寻找,但我没有看到任何与这里类似的问题。

Any help would be appreciated.

任何帮助,将不胜感激。

<?
require "functions2.php";
require "members.php";
$query = "SELECT MAX(DOCid) as prevDOCid from reports";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    $prevDOCid = $row[prevDOCid];

$thisDOCid = $prevDOCid+1;
$report = "a"."b".$thisDOCid;


}
echo $report;
?>

回答by Vilius

You could try to define the variable before the loop, e.g.

您可以尝试在循环之前定义变量,例如

$report = "";
while ($row = mysql_fetch_array($result)) {
    $report .= "a"."b".$row["prevDOCid"]+1;
}
echo $report;

I hope this helps you!

我希望这可以帮助你!

Edit Use .= not +=

编辑使用 .= 不是 +=