2011-10-08 216 views
0

我有一个相册阵列$albums[]和一组照片$photos。我想用每个相册的照片回显每张相册,并使用以下代码:PHP foreach循环嵌套

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

    <? 
    } 
} 

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

+0

你可以在第一个循环之外设置'$ limit',它总是不变的。如果你想改善代码味道,JRL的答案如下。 –

回答

2

我不会担心它是否看起来高效,而是它是干净的还是可维护的。因此,我建议你将代码分成两个功能,一个可以找到与专辑相关的所有照片,另一个可以创建用于显示它的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特定专辑阵列。

0

嗯,这是数组结构的问题。我认为你不能以更好的方式实现这一目标。这将是很高兴有照片元素内每个专辑元素在您的$相册数组,但你必须预先解析它,这将是无用的。