在symfony 2中的foreach

时间:2012-09-13 16:02:11

标签: php foreach

无法弄清楚如何每4次获取最后一个迭代行,但是我需要找到最后一行,这样我才能做到这一点

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

1 个答案:

答案 0 :(得分:2)

如果您正在使用Symfony2,那么您肯定不应该像这样呈现HTML内容,您应该使用模板引擎Twig

e.g。从控制器(我假设这是在控制器中):

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 %}