php 打破嵌套循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11609532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:52:14  来源:igfitidea点击:

Breaking the nested loop

phploopsnested-loops

提问by user1355300

I'm having problem with nested loop. I have multiple number of posts, and each post has multiple number of images.

我遇到了嵌套循环问题。我有多个帖子,每个帖子都有多个图片。

I want to get total of 5 images from all posts. So I am using nested loop to get the images, and want to break the loop when the number reaches to 5. The following code will return the images, but does not seem to break the loop.

我想从所有帖子中总共获取 5 张图片。所以我使用嵌套循环来获取图像,并希望在数字达到5时中断循环。以下代码将返回图像,但似乎没有中断循环。

foreach($query->posts as $post){
        if ($images = get_children(array(
                    'post_parent' => $post->ID,
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image'))
            ){              
                $i = 0;
                foreach( $images as $image ) {
                    ..
                    //break the loop?
                    if (++$i == 5) break;
                }               
            }
}

回答by dynamic

Unlike other languages such as C/C++, in PHP you can use the optional param of break like this:

与 C/C++ 等其他语言不同,在 PHP 中,您可以像这样使用 break 的可选参数:

break 2;

In this case if you have two loops such that:

在这种情况下,如果您有两个循环,则:

while(...) {
   while(...) {
      // do
      // something

      break 2; // skip both
   }
}

break 2will skip both while loops.

break 2将跳过两个 while 循环。

Doc: http://php.net/manual/en/control-structures.break.php

文档:http: //php.net/manual/en/control-structures.break.php

This makes jumping over nested loops more readable than for example using gotoof other languages

这使得跳过嵌套循环比使用goto其他语言更具可读性

回答by periklis

Use a while loop

使用while循环

<?php 
$count = $i = 0;
while ($count<5 && $query->posts[$i]) {
    $j = 0;
    $post = $query->posts[$i++];
    if ($images = get_children(array(
                    'post_parent' => $post->ID,
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image'))
            ){              
              while ($count < 5 && $images[$j]) { 
                $count++; 
                $image = $images[$j++];
                    ..
                }               
            }
}
?>