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

これが深刻な壊死であることはわかっていますが... Google からここにたどり着いたとき、他の人たちの混乱を防ごうと考えました。

彼がスイッチから抜け出して、数字のループを終わらせるbreak 2;つもりだったなら、それでよかったのに。数値のループを継続し、毎回 'dcontinue 2;になるように反復し続けます。continue

したがって、正解は のはずcontinue 3;です。

ドキュメントのコメントを続けると、基本的に構造の最後に移動します.switchはそれです(ブレークと同じように感じます)、ループは次の反復で取り上げます。

参照: 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 の文字のループを処理するだけでなく、数字のループの残りの部分も処理します ( $if の後にインクリメントと出力の両方が行われることに注意してください)。(これは望ましいかもしれないし、望ましくないかもしれません...)

最初にここにたどり着いた他の人の助けになることを願っています。

于 2014-06-18T17:17:18.977 に答える