是否有可能从开关断开,然后继续在循环中运行?
例如:$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'.
}
可以这样做吗?语法是什么?
您想使用break n
break 2;
澄清后,看起来您想要continue 2;
用continue 2
代替break
。
我知道这是一个严重的死亡,但是…当我从谷歌来到这里的时候,我想我可以为其他人避免困惑。
如果他的意思是从开关中跳出来,只是结束数字的循环,那么break 2;
就可以了。continue 2;
只会继续这个数字的循环,并不断迭代,每次都是continue
'd。
因此,正确答案应该是continue 3;
。
通过文档中的注释继续基本上到结构的末尾,for switch就是这样(感觉与break相同),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;
}
结果:
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之后打印)(这可能是也可能不是理想的…)
希望这能帮助到那些最先来到这里的人。