PHP foreach循环嵌套


PHP foreach loops nested

我有一个相册数组$albums[]和照片数组$photos。我想用所有匹配的照片回显每个相册,并使用此代码:

<?php
    ...
    foreach($albums as $album){
        if( $album[photo_count] !== 0 ){
            if($album[photo_count] > 10){
                $limit = 10;
            }
            $boxID = $id = substr( $album[aid], strrpos( $album[aid], '_' )+1 );     
?>
            <div id="gal-<?=$boxID?>-box" class="box gallery-album">
            <?
            $i = 0;
            foreach($photos as $photo){                             
                if( ($photo[aid] == $album[aid]) && ($i < $limit) ){
                    echo '<img src="'.$photo[src_big].'" alt="'.$photo[caption].'"/>';
                    $i++;
                }
        } 
    ?>
    </div>
    </div>
    <?
    }   
}

这工作得很好,但感觉效率很低。有没有更好的编码方式?

我不担心它是否看起来有效,而是担心它是否干净和可维护。

因此,我建议您将代码分成两个函数,一个用于查找与相册相关的所有照片,另一个用于创建用于显示它的html,例如:
/**
 * Gets the photos for a given album
 * @param int $albumId the album identifier
 * @return array an array of photos associated with this album,
 *               or an empty array if there are none
 */
function getPhotos($albumId);
/**
 * Outputs an html div for each photo in the photo array
 * @param array $photos an array of photos
 */
function displayPhotos($photos);

您还可以使用一些SPL迭代器来使代码更简洁,例如LimitIterator,您将使用它来限制传递给给定相册的displayPhotos的数组。

这是数组结构的问题。我认为没有比这更好的办法了。在$albums数组中的每个album元素中都有photos元素是很好的,但是必须预先解析它,这将是无用的。