按日期排序的各组 [英] Twig foreach group by date

查看:114
本文介绍了按日期排序的各组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子上有足球比赛,叫做'比赛'。在该表中有一个开球字段,它是比赛开始时的日期时间栏。

  $ matches = $ em-> createQueryBuilder()$ ('Football':Match','m')
- > addOrderBy('m.kickoff','ASC')
- > getQuery()
- > getResult();
$ b $ return $ this-> render('FootballWcBundle:Page:matches.html.twig',array(
'matches'=> $ matches
));

现在我想在日期分组的屏幕上显示比赛。
像这样:



12-12-2014



match1



match2

14-12-2014

match3



match4

match5



有没有办法让Twig知道在开球专栏进行分组还是有另外一种方法来做到这一点?

  {%set date = null%} 
{%匹配匹配%}
{%if date! = match.kickoff%}
{%set date = match.kickoff%}
< h3> {{date}}< / h3>
{%endif%}

< p> {{match.name}}< / p>
{%endfor%}

通过这种方式,您可以将第一个日期设置为null,你迭代所有的匹配,并写一个名字为'p'的标签(我假设这个匹配有一个名字来做这个例子),当匹配的日期发生变化时,你写一个'h3'标签,其日期是比赛。由于日期在第一次迭代中设置为空,第一个日期将写入。


I have a table with football matches called 'matches'. In that table there is a field 'kickoff', which is a datetime-column of the time when the match starts. With the following code I get all the matches out of the table.

$matches = $em->createQueryBuilder()
        ->select('m')
        ->from('FootballWcBundle:Matches', 'm')
        ->addOrderBy('m.kickoff', 'ASC')
        ->getQuery()
        ->getResult();

return $this->render('FootballWcBundle:Page:matches.html.twig', array(
        'matches' => $matches
));

Now I want to show the matches on the screen grouped by the date. Like this:

12-12-2014

match1

match2

14-12-2014

match3

match4

match5

Is there a way to let Twig know to group by the kickoff column or is there another way to do this?

解决方案

You could do that as below:

    {% set date = null %}
    {% for match in matches %}
        {% if date != match.kickoff %}
            {% set date = match.kickoff %}
            <h3>{{ date }}</h3>
        {% endif %}

        <p>{{ match.name }}</p>
    {% endfor %}

In this way, you set the first date as null, and you iterate all matches and write a 'p' tag with the name (I supposed the match had a name to do the example), and when the date of the matches changes, you write a 'h3' tag with the date of the match. As date is set to null in the first iteration, the first date will be write.

这篇关于按日期排序的各组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆