从开关'断开',然后在循环中'继续'

Dre*_*rew 7 php control-structure

是否有可能从开关断开然后继续循环?

例如:

$numbers= array(1,2,3,4,5,6,7,8,9,0);
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g');

foreach($letters as $letter) {
    foreach($numbers as $number) {
        switch($letter) {
           case 'd':
               // So here I want to 'break;' out of the switch, 'break;' out of the
               // $numbers loop, and then 'continue;' in the $letters loop.
               break;
        }
    }

    // Stuff that should be done if the 'letter' is not 'd'.

}
Run Code Online (Sandbox Code Playgroud)

可以这样做,语法是什么?

Eri*_*ric 16

你想用 break n

break 2;
Run Code Online (Sandbox Code Playgroud)

澄清后,看起来像你想要的 continue 2;


ant*_*ell 9

而不是break,使用continue 2.

  • 程序将返回到数字循环的开头。这是 php 独有的。你可以在这里查看=>http://www.php.net/manual/en/control-structures.switch.php (2认同)

not*_*uch 5

我知道这是一个严重的坏事,但是...当我从Google到达这里时,我想避免了其他人的困惑。

如果他想退出交换机并只是结束数字的循环,那break 2;就没问题了。continue 2;只会继续数字的循环,并不断循环遍历,以便continue每次都被“ d”。

嗯,正确的答案应该是continue 3;

通过去在文档评论不断基本上进入到结构的末尾,用于交换机就是这样(会觉得一样休息),for循环它会拿起下一次迭代。

请参阅:http//codepad.viper-7.com/dGPpeZ

超过n / a的示例:

<?php
    echo "Hello, World!<pre>";

$numbers= array(1,2,3,4,5,6,7,8,9,0);
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');

$i = 0;
foreach($letters as $letter) {
    ++$i;
    echo $letter . PHP_EOL;
    foreach($numbers as $number) {
        ++$i;
        switch($letter) {
           case 'd':
               // So here I want to 'break;' out of the switch, 'break;' out of the
               // $numbers loop, and then 'continue;' in the $letters loop.
              continue 3; // go to the end of this switch, numbers loop iteration, letters loop iteration
            break;
           case 'f':
            continue 2; // skip to the end of the switch control AND the current iteration of the number's loop, but still process the letter's loop
            break;
           case 'h':
            // would be more appropriate to break the number's loop
            break 2;

        }
        // Still in the number's loop
        echo " $number ";
    }


    // Stuff that should be done if the 'letter' is not 'd'.
    echo " $i " . PHP_EOL;

}
Run Code Online (Sandbox Code Playgroud)

结果:

Hello, World!
a
 1  2  3  4  5  6  7  8  9  0  11 
b
 1  2  3  4  5  6  7  8  9  0  22 
c
 1  2  3  4  5  6  7  8  9  0  33 
d
e
 1  2  3  4  5  6  7  8  9  0  46 
f
 57 
g
 1  2  3  4  5  6  7  8  9  0  68 
h
 70 
i
 1  2  3  4  5  6  7  8  9  0  81 
Run Code Online (Sandbox Code Playgroud)

continue 2;不仅处理字母d的字母循环,甚至处理数字的其余循环(请注意,该循环$i在f之后递增并打印)。(可能不希望...)

希望对其他先到这里的人有所帮助。