PHP:打破嵌套循环

时间:2012-07-23 09:12:33

标签: php loops

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

我想从所有帖子中共获得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;
                }               
            }
}

2 个答案:

答案 0 :(得分:142)

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

break 2;

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

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

      break 2; // skip both
   }
}

break 2将跳过两个while循环。

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

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

答案 1 :(得分:3)

使用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++];
                    ..
                }               
            }
}
?>
相关问题