code

PHP : 중첩 루프 끊기

codestyles 2020. 12. 3. 07:52
반응형

PHP : 중첩 루프 끊기


이 질문에 이미 답변이 있습니다.

중첩 루프에 문제가 있습니다. 여러 개의 게시물이 있고 각 게시물에는 여러 개의 이미지가 있습니다.

모든 게시물에서 총 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;
                }               
            }
}

C / C ++와 같은 다른 언어와 달리 PHP에서는 다음과 같이 break의 선택적 매개 변수를 사용할 수 있습니다.

break 2;

이 경우 다음과 같은 두 개의 루프가있는 경우 :

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

      break 2; // skip both
   }
}

break 2 while 루프를 모두 건너 뜁니다.

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

예를 들어 goto다른 언어 를 사용 하는 것보다 중첩 된 루프를 더 읽기 쉽게 건너 뜁니다.


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++];
                    ..
                }               
            }
}
?>

참고 URL : https://stackoverflow.com/questions/11609532/php-breaking-the-nested-loop

반응형