2010-11-24 81 views
33

如果某些條件不符合,我試圖跳到循環的下一次迭代。問題是無論如何循環都在繼續。PHP的foreach繼續

我在哪裏出了錯?

更新後的代碼示例以迴應第一條評論。

foreach ($this->routes as $route => $path) { 
     $continue = 0; 

     ... 

     // Continue if route and segment count do not match. 
     if (count($route_segments) != $count) { 
      $continue = 12; 
      continue; 
     } 

     // Continue if no segment match is found. 
     for($i=0; $i < $count; $i++) { 
      if ($route_segments[$i] != $segments[$i] && ! preg_match('/^\x24[0-9]+$/', $route_segments[$i])) { 
       $continue = 34; 
       continue; 
      } 
     } 

     echo $continue; die(); // Prints out 34 
+1

您正在覆蓋`$ continue`。在循環迭代中完全可以輸入它被設置爲1,然後是2。 – 2010-11-24 18:11:25

+1

在`foreach`之後設置`$ continue = 0;`...我敢打賭你不會再擁有`1`。對於2,你需要告訴它繼續2個級別,所以`繼續2;`,否則它只會去`for`循環的下一個迭代... – ircmaxell 2010-11-24 18:14:44

回答

87

如果你想有你的第二個continue適用於foreach循環,你必須把它從

continue; 

改變

continue 2; 

這將指示PHP應用continue聲明到第二個嵌套循環,即foreach循環。否則,它將僅適用於for循環。

11

第二個繼續處於另一個循環中。這個只會「重啓」內循環。如果你想重新啓動外循環,你需要給繼續暗示它應該多少環路上去

continue 2; 

Manual

0

continuefor環路內將for循環中跳過,而不是foreach循環。

7

您在for循環中調用continue,因此將繼續執行for循環,而不是foreach循環。使用:

continue 2;