【问题标题】:ordering an array of object with twig用树枝订购一个对象数组
【发布时间】:2019-01-23 10:52:52
【问题描述】:

我需要订购带有内部属性的对象列表。

I receive a list of objects like that :
{ match: "italy - germany", date: "27/01/2019", competion: "World cup" }
{ match: "lille - paris", date: "23/01/2019", competion: "coupe de france" }
{ match: "om - psg", date: "13/01/2019", competion: "coupe de france" }
{ match: "russia - poland", date: "25/01/2019", competion: "World cup" }

我不知道从哪里开始,但我需要循环匹配: {% for match in matches %}

我想获取这个列表:

法国杯:

​​>
  • om - psg
  • 里尔-巴黎

世界杯:

​​>
  • 意大利德国
  • 俄罗斯 - 波兰

【问题讨论】:

标签: twig


【解决方案1】:
{% set data = [
    {
        'country' : 'france',
        'match': 'G',
    },
    {
        'country' : 'belgium',
        'match': 'F',
    },
    {
        'country' : 'france',
        'match': 'E',
    },
        {
        'country' : 'germany',
        'match': 'D',
    },
    {
        'country' : 'germany',
        'match': 'C',
    },
        {
        'country' : 'france',
        'match': 'B',
    },
    {
        'country' : 'italy',
        'match': 'A',
    },  
] %}


{% set sorted = [] %}
{% for row in data %}
    {% if not ((row.country) in sorted|keys) %}{% set sorted = sorted|merge({ (row.country) : [], }) %}{% endif %}
    {% set sorted = sorted|merge({(row.country): (sorted[(row.country)]|merge([ row.match, ])|sort)}) %}
{% endfor %}

{% for country, values in sorted %}
    {{ country }}
    {% for value in values %}
        - {{ value }}
    {% endfor %}
----------------------------
{% endfor %}

demo

【讨论】:

    【解决方案2】:

    你可以试试snilius/twig-sort-by-field

    有了这个 Twig 扩展,你可以做这样的事情:

    {% for match in matchs|sortbyfield('competion', 'desc') %}
        {{ dump(match) }}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2017-10-14
      相关资源
      最近更新 更多