PHP,继续; on foreach(){foreach(){

Mer*_*kos 36 php foreach

如果内部的foreach符合某些声明,是否有办法继续使用外部foreach?

在例子中

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue; // But not the internal foreach. the external;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*254 81

试试这个,应该工作:

continue 2;
Run Code Online (Sandbox Code Playgroud)

从PHP手册:

继续接受一个可选的数字参数,该参数告诉它应跳过多少级别的封闭循环到结尾.

这里是您需要的示例(准确的第2个)描述的代码


mat*_*ino 12

试试这个:continue 2;根据手册:

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. 
Run Code Online (Sandbox Code Playgroud)


Mar*_*cus 6

这种情况有两种解决方案,使用breakcontinue 2.请注意,当使用break来突破内部循环时,仍然会执行内部循环之后的任何代码.

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            break;
        }
    }
    echo "This line will be printed";
}
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是使用continue接下来继续多少级别.

foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue 2;
        }
    }
    // This code will not be reached.
}
Run Code Online (Sandbox Code Playgroud)


JND*_*PNT 5

这将继续高于(因此外部 foreach)

 continue 2
Run Code Online (Sandbox Code Playgroud)


meg*_*lop 5

<?php
foreach($c as $v)
{
    foreach($v as $j)
    {
        if($j = 1)
        {
            continue 2; // note the number 2
        }
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

RTM