Break While和Foreach循环

时间:2014-03-24 15:04:54

标签: php

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

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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

你可以:

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")

答案 1 :(得分:0)

你应该使用中断符号:

    $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
相关问题