2012-09-13 78 views
-2

有麻煩工作如何獲得最後的迭代行,每4把它的,但我需要找到最後一個,所以我可以作出這樣的做一些事情的foreach symfony的2

foreach($gallery->getMedia() as $key => $media) 
{ 
     if(($key % 4) == 0) $html .= '<div class="clear"></div>'; 
     $url = $media->dir . '/' . $media->filename; 

     $html .= sprintf('<li><a href="#photo-%s" class="album_image_wrapper" id="photo_%s" title="%s" alt="%s" target="_blank" class="image-link" rel="slideshow"><div style="background-image: url(\'', 
       $media->id , 
       $media->id , 
       $url, 
       $gallery->name , 
       $media->id , 
       $this->generateThumbUrl($url, array('width' => 100, 'height'=> 120, 'zoom' => true)), 
       $media->title, 
       $galleryID ); 

回答

2

如果你使用Symfony2,那麼你肯定不應該像這樣渲染HTML內容,你應該使用模板引擎Twig

例如從控制器(我想這是在控制器):

return $this->render('BundleName:ControllerName:view.html.twig', array(
    'gallery' => $gallery 
); 

然後在您的/path/to/BundleName/Resources/views/ControllerName/view.html.twig模板:

{% for key, media in gallery.media %} 
    {% if loop.last %} 
     {# Logic for the last iteration of the loop #} 
    {% endif %} 

    {% if loop.index % 4 == 0 %} 
     {# Logic for every 4th iteration #} 
    {% endif %} 

    {# other code... #} 

{% endfor %}