10

是否可以从开关中断然后继续循环?

例如:

$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'.

}

这可以做到吗,语法是什么?

4

3 回答 3

18

你想用break n

break 2;

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

于 2011-11-20T22:57:02.620 回答
10

而不是break,使用continue 2.

于 2011-11-20T23:22:24.540 回答
5

我知道这是一个严重的死灵,但是......当我从谷歌来到这里时,我想我会避免其他人的困惑。

如果他的意思是从交换机中跳出来并结束数字的循环,那就没问题break 2;了。continue 2;只会继续数字的循环并不断迭代它只是为了continue每次都被'd'。

因此,正确答案应该是continue 3;

通过文档中的注释continue 基本上到结构的末尾,对于 switch 就是这样(感觉与 break 相同),对于循环它会在下一次迭代中拾取。

见: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;

}

结果:

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 

continue 2;不仅处理字母 d 的字母循环,甚至处理数字循环的其余部分(注意$i在 f 之后增加和打印)。(这可能是可取的,也可能不是可取的......)

希望这可以帮助其他首先在这里结束的人。

于 2014-06-18T17:17:18.977 回答