简体   繁体   English

在while循环中中断while循环

[英]Break while loop inside for loop

How can I break while loop and for loop too when while loop is true? 当while循环为true时,如何同时中断while循环和for循环?

<?php
for($i=0; $i<4; $i++){
    $result = mysql_query("SELECT * FROM table WHERE weight='$i'");
    while($row = mysql_fetch_array($result)){
        echo $row['cell'];
        break; //I need to break the while loop and the for loop too in this line exactly, when he find and echo the "cell"!
    }
}
?>

It is 它是

break 2;

References: 参考文献:

... ...

Use Flags: 使用标志:

One flag inside while : Set this flag to 1 when you break while while内一个标志:当while中断时,将此标志设置为1

One flag in outer for loop: If while loop flag is set then break for loop 外部for循环中的一个标志:如果设置了while循环标志,则中断for循环

Instead of doing a break why not do the following 除了break为什么不做以下事情

SELECT * FROM table WHERE weight BETWEEN 0 AND 3

OR just 要不就

SELECT * FROM table WHERE weight = 0

You would be limiting querying the database multiple times and probably takes less time but you'd wouldn't notice it with a query like this. 您将限制多次查询数据库,并且可能花费更少的时间,但是您不会在这样的查询中注意到它。

Not sure why you there is a for loop then break on first iteration when you can just query the database and echo something. 不确定为什么会有for循环,然后在仅查询数据库并回显某些内容时就在第一次迭代时中断。 Unless OP has other plans for this code and reduced the code for SO the loop is really unnecessary. 除非OP对此代码有其他计划并减少SO的代码,否则确实不需要循环。

use exit instead of break . 使用exit而不是break

break results exit from current iteration while exit results exit from overall pgm. break结果从当前迭代退出,而退出结果从总体pgm退出。

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

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