N
N
nikkon822019-10-11 11:35:27
opencart
nikkon82, 2019-10-11 11:35:27

How to sort the list of cities by the first letter and by blocks A, B, C, etc.?

Good afternoon!
There is a list of cities, which is derived from an array and sorted by the first letter of the alphabet.
How to make it not just a list, but divided into blocks by the first letter - A, B, C, etc.
Here is the array output code:

<div>
        {% for city in cities %}
            <div class="cities_city">
                  <a class="cities_city-name" data-id="{{ city.fias_id }}">
                    {{ city.name }}
                  </a>
                </div>
              {% endfor %}
            </div>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Moses Fender, 2019-10-11
@mosesfender

The array is still sorted first, and then output.

K
kikimarik, 2019-10-11
@kikimarik

Well, something like that.

$cities = ['Moscow', 'London', 'NY', 'LA'];
sort($cities);
$citiesByLetters = [];

foreach ($cities as $city) {
                
    $citiesByLetters[$city[0]][] = $city;
}

foreach ($citiesByLetters as $letter => $cities) {
                
    echo '<div id="letter-'.$letter.'">';

    foreach ($cities as $city) {
                    
        echo '<div class="city-el">'.$city.'</div>';
    }

    echo '</div>';
}

If city names are in utf-8, then use mb_substr($city, 0, 1, 'UTF-8') to determine the first letter of the city instead of $city[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question