Search code examples
twigcraftcms

Craft/Twig How to loop multiple key/value pairs and remove duplicates from that loop?


In Craft CMS, I have child entries where each child has a location with "city" and "country" values assigned to it.

I'm looking to output a list of "City, Country" text but remove any duplicates as two or more children might share the same "city,country" pair.

It's important that I can reference the city and country value for each child separately, because I need to use the country value for displaying a flag for each child item in the list.

I've learned about and tried my hand at "twig hash" and "associative arrays" and found usable snippets but can't make it work together for my case.

This does not work:

{% set children = entry.children %}

{% set locations = {} %}

{% for child in children %}
    {% set city = child.location.parts.locality %}
    {% set country = child.location.parts.country %}

    {% if city not in locations %}
        {% set locations = locations|merge({ city : country }) %}
    {% endif %}

{% endfor %}

{% for location in locations %}
    {% for k, v in location %}
        {{ k }}, {{ v }} <br />
    {% endfor %}
{% endfor %}

Solution

  • If you want to let the city be the key of your array you will need to wrap them in parantheses so the variable will get interpreted by twig.

    Also you don't need the double for loop, you are building a one dimensional array

    {% set locations = {} %}
    
    {% for child in children %}
        {% set city = child.city %}
        {% set country = child.country %}
    
        {% if city not in locations %}
            {% set locations = locations|merge({ (city) : country }) %}
        {% endif %}
    
    {% endfor %}
    
    {% for k,v in locations %}
        {{ k }}, {{ v }} <br />
    {% endfor %}
    

    demo