Create structured object from query results I'm trying to create a list of countries with a sublist of territories per country based on their existence in the same record. The following is shorthand pseudocode to illustrate:

    locations =&gt;
         United States =&gt;
             California
             Massachusettes
             New York
         France =&gt;
             Lille
             Marseille


Here is my code so far:

   {% set allEntries = craft.entries.section('projects').limit(2000) %}
   {% set countries = allEntries|group('country') %}
   {% set country_arr ={} %}

   {% for country, entriesInCountry in countries %}

       {% if not attribute(country_arr, country) is defined %}

         {# Add country to list, if unique #}

         {% set country_arr = country_arr | merge([country]) %} 

       {% endif %}

       {% for entry in entriesInCountry %}

          {# Somehow add the entry.state here as a property or sub-object of the country, if unique #}

       {% endfor %}
  {% endfor %}
Definitely not the most efficient way to do this (it'd be cleaner and more efficient with PHP), but assuming you have  "projects" section that has a "country" Plain Text field and it also had a "state" Plain Text field and you wanted to group projects by country and then state, something like this should work:

{% set countryArr = {} %}

{# grab all projects #}
{% set allEntries = craft.entries.section('projects').limit(null) %}

{# group them by country #}
{% set countries = allEntries|group('country') %}

{# Build the nested array structure #}
{% for country, projects in countries %}
    {# if it's a new country, add it to our structure #}
    {% if countryArr[country] is not defined %}
        {% set countryArr = countryArr|merge({(country):[]}) %}
    {% endif %}

    {# loop through all of the projects in that country #}
    {% for project in projects %}
        {# see if we have a record for the state yet #}
        {% if project.state not in countryArr[country] %}
            {# because twig isn't great with multidimensional arrays #}
            {% set tempArr = countryArr[country] %}
            {% set tempArr = tempArr|merge([project.state]) %}

            {# merge back into our main structure indexed by country #}
            {% set countryArr = countryArr|merge({(country):tempArr})  %}
        {% endif %}
    {% endfor %}
{% endfor %}

{# output our structure #}
{% for country, projects in countryArr %}
    &lt;ul&gt;
        &lt;li&gt;{{ country }}
            &lt;ul&gt;
                {% for project in projects %}
                    &lt;li&gt;{{ project }}&lt;/li&gt;
                {% endfor %}
            &lt;/ul&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
{% endfor %}