我遇到嵌套循环问题.我有多个帖子,每个帖子都有多个图片.
我希望从所有帖子中共获得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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
dyn*_*mic 153
与其他语言(如C/C++)不同,在PHP中,您可以像这样使用可选的break中断:
break 2;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果你有两个循环,这样:
while(...) {
while(...) {
// do
// something
break 2; // skip both
}
}
Run Code Online (Sandbox Code Playgroud)
break 2 将跳过两个while循环.
Doc:http://php.net/manual/en/control-structures.break.php
这使得跳过嵌套循环比使用goto其他语言更具可读性