【问题标题】:PHP, continue; on foreach(){ foreach(){PHP,继续;在 foreach(){ foreach(){
【发布时间】:2011-12-11 16:35:32
【问题描述】:

如果内部 foreach 遇到某些声明,有没有办法继续外部 foreach ?

举例

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

【问题讨论】:

  • 看起来你可以......你必须指定它应该继续多少级别......在你的情况下继续2;更多信息在这里php.net/manual/en/control-structures.continue.php
  • 如果你用数据和原因解释真实案例,你会得到更合适的答案。 -1 到目前为止,因为极度简洁和模糊。
  • -1 也是因为在提出这个问题之前还没有做太多的研究。甚至没有看手册。
  • 不管 SO 标准如何,这都是 google 上的最高结果。因此,我提供以下内容……这可能是代码异味。在某些情况下,将内部循环包装在另一个函数/方法中可能是个好主意。

标签: php foreach


【解决方案1】:

试试这个,应该可以的:

continue 2;

来自 PHP 手册:

Continue 接受一个可选的数字参数,告诉它应该跳到多少层封闭循环。

here 在示例中(确切地说是第二个)描述了您需要的代码

【讨论】:

    【解决方案2】:

    对于这种情况有两种可用的解决方案,使用breakcontinue 2。请注意,当使用 break 跳出内部循环时,内部循环之后的任何代码仍将被执行。

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

    另一种解决方案是使用continue,后跟要从多少级返回继续。

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

    【讨论】:

      【解决方案3】:

      如果我没听错的话,你必须使用break 而不是继续

      这里我写了关于此事的解释:What is meant by a number after "break" or "continue" in PHP?

      【讨论】:

      • 不,他没有——他只是在continue 之后添加了一个数字,正如其他人所指出的那样。
      【解决方案4】:

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

      continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. 
      

      【讨论】:

        【解决方案5】:
        <?php
        foreach($c as $v)
        {
            foreach($v as $j)
            {
                if($j = 1)
                {
                    continue 2; // note the number 2
                }
            }
        }
        ?>
        

        RTM

        【讨论】:

        • 由于某种原因,每个引用 continue 2 的答案都被某人否决了一次......
        【解决方案6】:

        这将继续到上面的级别(所以外部 foreach)

         continue 2
        

        【讨论】:

          【解决方案7】:

          尝试break 而不是continue

          您可以在break 后面加上一个整数,给出要跳出的循环数。

          【讨论】:

            猜你喜欢
            • 2011-05-15
            • 1970-01-01
            • 2010-10-11
            • 1970-01-01
            • 2022-08-09
            • 2017-09-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多