繁体   English   中英

Break While和Foreach循环

[英]Break While and Foreach Loop

我有下面的代码,我的问题是,如果用户输入“n”并继续下一个foreach interation,我想要打破while循环。 请参阅我的评论。

foreach($nodeid as $nid){

    $query= $dbh->query("SELECT * FROM Nodes WHERE Node_ID = '$nid' AND New = 1")or die(mysql_error());

    if($query->rowCount() > 0)
    { 
        while (1) {
            fputs(STDOUT, "\n"."***New Node*** : $nid \n Do you want to add ? [y,n]: ");
            $response = strtolower(trim(fgets(STDIN)));
            if( $response == 'y' ) {
                #do something then break and go to next foreach.
            } elseif( $response == 'n' ) {
                #go to next foreach $nid
            } else {
                echo "\n", "I don't understand your option, let's try this again", "\n";
                continue;
            }
        }
    }
}

您可以:

continue 2;

在这种情况下。 这将继续下一次外部foreach循环运行。

但是,正如@Tularis在评论中所说,一个简单的break在这里会产生相同的效果,因为没有代码跟随while循环。 (可能更容易阅读)


关于查询。 看起来在这里使用IN语句只为所有id发出一个数据库查询会更好:

$ids = impldode(',', $nodeids); // assuming the ids are integers
$query= $dbh->query("SELECT * FROM Nodes WHERE Node_ID IN $ids AND New = 1")

你应该使用break符号:

    $foreach = array('a','b','c','d');
    $while = array('a','b','c','d');
    foreach($foreach as $key => $value){
        echo 'in foreach = '. $value.'<br/>';
        reset($while);
        while(current($while)){
            echo '&nbsp;&nbsp; in while = '. current($while).'<br/>';
            if(current($while) == 'b'){
                break;
            }
            next($while);
        }
    }

结果:

in foreach = a
   in while = a
   in while = b
in foreach = b
   in while = a
   in while = b
in foreach = c
   in while = a
   in while = b
in foreach = d
   in while = a
   in while = b

暂无
暂无

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

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