php While 循环和多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11977195/
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-25 02:33:04  来源:igfitidea点击:

While Loops and Multiple Conditions

php

提问by jason328

Is it possible to write multiple conditions in a while loop? If not, what is an alternative? I tried it and was returned with an error relating the line of code that sets up the conditions for the while loop. Here is an example of what I mean.

是否可以在 while 循环中编写多个条件?如果没有,有什么替代方案?我尝试了它并返回一个错误,该错误与设置 while 循环条件的代码行有关。这是我的意思的一个例子。

$s = 1;

while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}

回答by Mark Byers

That is possible, but because =has lower precedencethan &&you need parentheses to ensure that your statement is interpreted correctly:

这是可能的,但由于=具有较低的优先级&&你需要括号以确保您的语句是正确解释:

while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))

The parentheses around $s < 5are not required here, but I've included them for clarity.

$s < 5此处不需要括号,但为了清楚起见,我将它们包括在内。

However it would be easier just to modify your query to only return 5 rows, by adding LIMIT 5.

但是,通过添加LIMIT 5.

SELECT ...
FROM yourtable
ORDER BY ...
LIMIT 5

回答by JoeTomato

You could try:

你可以试试:

$s=1
while ($result_row = mysql_fetch_assoc($query))
{
    echo $result_row['id'];
    $s++;
    if($s>5){
        break;
    }
}

http://php.net/manual/en/control-structures.break.php

http://php.net/manual/en/control-structures.break.php

回答by Ibrahim Azhar Armar

while i see nothing wrong in that. the other way round is to do something like this.

虽然我认为这没有错。另一种方式是做这样的事情。

$s = 1;
while ($result_row = mysql_fetch_assoc($query))
{
    if($s < 5) {
        //enter the condition
    }
    $s++;
}

回答by Mike Christensen

The value of $result_rowis probably being set to the Boolean condition of whether mysql_fetch_assoc($query)returns something true-ish and $sis less than 5. So trying to read $result_rowas a dictionary no longer works.

的值$result_row可能被设置为是否mysql_fetch_assoc($query)返回真实值的布尔条件并且$s小于 5。因此尝试将其$result_row作为字典阅读不再有效。

You can use parenthesis to specify exactly how things get parsed:

您可以使用括号来准确指定解析内容的方式:

while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))

This way, $result_rowgets set to mysql_fetch_assoc($query), which is what you want, andthe loop continues as long as the logical value of that assignment returns something true-ish, as well as sis less than 5.

这样一来,$result_row被设置为mysql_fetch_assoc($query),这是你想要的东西,循环继续,只要该转让收益东西真十岁上下的逻辑值,以及s小于5。