开发者

PHP foreach loops nested

开发者 https://www.devze.com 2023-04-11 20:42 出处:网络
I have an array of albums $albums[] and an array of photos $photos. I want to echo out each album with all matching photos and am using this code:

I have an array of albums $albums[] and an array of photos $photos. I want to echo out each album with all matching photos and am using this code:

<?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>

    <?
    }   
}

This works fine, but feels very inefficient. Is there a better way of coding this?


I wouldn't worry about whether or not it seems efficient, but rather whether it is clean and maintainable.

As such, I would suggest you separate the code into two functions, one which finds all photos associated with an album, and one which creates the html for displaying it, e.g. something like:

/**
 * 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);

You can also use some of the SPL iterators to make the code cleaner, such as LimitIterator, which you would use to limit the array passed to displayPhotos for a given album.


Well, it's a problem of how your arrays are structured. I don't think you could achieve this in a better way. It'd be nice to have the photos element inside each album element in your $albums array, but you'd have to pre-parse it, which would be useless.

0

精彩评论

暂无评论...
验证码 换一张
取 消