2

Using the following filter will return all the entries for 'CA'.

{% set params = {
    filter: {
        state: 'CA'
    }
} %}

{% set meetings = craft.entries.address(params) %}

Let's say that I get 10 returns for 'CA':

Los Angeles
Los Angeles
Los Angeles
San Diego
San Diego
San Diego
San Diego
San Diego
San Diego
Modesto

How would I go about one getting 3 results returned for each unique value for City? I only want to list each city once rather than 3 Los Angeles, 16 San Diego's and 1 Modesto. Like this:

Los Angeles
San Diego
Modesto

It could also be helpful to have them like this:

3 Los Angeles
6 San Diego
1 Modesto

I am building a navigation by state with a list of cities under each state. To look like this:

CA
   Los Angeles
   San Diego
   Modesto
KS
   Wichita
   Kansas City

1 Answer 1

3

You'd actually need to retrieve all of the entries to count them in this way. Once you've got the complete collection, it would simply be a matter of looping through them and adding everything up.

1. Get all entries in California.

{% set params = {
    filter: {
        state: 'CA'
    }
} %}

{% set meetings = craft.entries.address(params).all() %}

2. Loop through those entries. Build a new array based on the results.

{% set stateMeetings = {} %}
    
{% for meeting in meetings %}

    {% set city = meeting.address.city %}

    {% if stateMeetings[city] is defined %}
        {% set cityTotal = stateMeetings[city] + 1 %}
    {% else %}
        {% set cityTotal = 1 %}
    {% endif %}

    {% set stateMeetings = stateMeetings|merge{(city):cityTotal} %}

{% endfor %}

3. By the time that's all done, you'll have a neat associative array, where each key is a different city, and the value of each represents how many times it was found.

{
    "Los Angeles": 3,
    "San Diego": 6,
    "Modesto": 1,
}

You'll definitely want to cache all of that... it'll be a pretty expensive process.

To be honest, I'd actually recommend doing all of this work in a plugin (or module). It's a fairly easy thing to achieve with a template hook. This kind of heavy merging is ill-fitted for Twig, but much simpler in PHP.

1
  • Thanks. Yeah, I am learning plugins now. Pretty easy to do with sql directly in the table. Haven't looked at modules yet at all. Mar 20, 2018 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.