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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度