Search code examples
phptwig

Remove duplicate data from the Twig object and combine it


In my Twig template i have list, something like this:

1985 - John
1974 - Lena
1985 - Sandra
1974 - Tom
1985 - Jess

The year can be duplicated. So i need combine my list like this:

1985 - John, Sandra, Jess
1974 - Lena, Tom

Is it possible to do this in the Twig template engine?


Solution

  • In Twig, we can add data to an array with the merge filter.

    The tricky parts:

    • we have to merge the names for each year and then merge it to the main array, with the year as the key
    • Twig resets the key to a number (0, 1, etc.) if we try to use a number as a key

    If we have this data:

    {% set data = [
      {"year": 1985, "name": "John"},
      {"year": 1974, "name": "Lena"},
      {"year": 1985, "name": "Sandra"},
      {"year": 1974, "name": "Tom"},
      {"year": 1985, "name": "Jess"},
    ]
    %}
    

    We can loop over it, and create an array, with each year as the key and the names as values:

    {% set groupedData = {} %}
    
    {# Loop over data #}
    
    {% for person in data -%}
        {# the year must be casted as a string, otherwise it uses numeric keys in the array #}
        {% set year = "y" ~ person["year"] %}
        {% set name = person["name"] %}
      
        {% if year not in groupedData|keys %}
            {# year doesn't exist in the array, add a key with the year and an array with one name #}
            {% set groupedData = groupedData|merge({(year): [name]}) %}
        {% else %}
            {# year exists in the array, add the name to the array of names for this year #}
            {% set newNamesForYear = attribute(groupedData, year)|merge([name]) %}
            {% set groupedData = groupedData|merge({(year): newNamesForYear}) %}
        {% endif %}
    {% endfor %}
    
    

    And display the result:

    {% for year, names in groupedData %}
        {# remove the y in the year and print the names #}
        {{ year|slice(1) }} - {{ names|join(', ') }}
    {% endfor %}
    

    Here is the result:

    1985 - John, Sandra, Jess
    1974 - Lena, Tom
    

    Try it online on TwigFiddle.

    Resources used: