duanqian2368 2011-10-08 12:40
浏览 62
已采纳

PHP foreach循环嵌套

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?

  • 写回答

2条回答 默认 最新

  • dquh37673 2011-10-08 13:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上