ordering an array of object with twig

2019-08-21 07:51发布

问题:

I need to order a list of objects i receive with an inner property.

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

I don't know where to start but i need to loop over matches: {% for match in matches %}

I want to obtain this list:

coupe de france :

  • om - psg
  • lille -paris

world cup :

  • italy germany
  • russia - poland

回答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:

You can try snilius/twig-sort-by-field.

With this Twig extension, you can do somthing like this:

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


标签: twig