打破嵌套循环 [英] Breaking the nested loop
问题描述
我在嵌套循环方面遇到问题.我有多个帖子,每个帖子都有多个图片.
I'm having problem with nested loop. I have multiple number of posts, and each post has multiple number of images.
我想从所有帖子中获取总计5张图片.因此,我使用嵌套循环获取图像,并希望在数字达到5时中断循环.以下代码将返回图像,但似乎没有中断循环.
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.
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;
}
}
}
推荐答案
与其他语言(例如C/C ++)不同,在PHP中,您可以使用如下所示的可选break参数:
Unlike other languages such as C/C++, in PHP you can use the optional param of break like this:
break 2;
在这种情况下,如果您有两个循环,那么:
In this case if you have two loops such that:
while(...) {
while(...) {
// do
// something
break 2; // skip both
}
}
break 2
将跳过两个while循环.
break 2
will skip both while loops.
文档: http://php.net/manual/en/control- structure.break.php
与使用其他语言的goto
相比,这使跳过嵌套循环更具可读性
This makes jumping over nested loops more readable than for example using goto
of other languages
这篇关于打破嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!