Sort collection alphabetically with latin chars

Hi, I have a list of users that I want to sort alphabetically by surname, so far so good but when there is a latin character, the order is altered.

Something like:

$users = $kirby->users()->sortBy('lastname');

When a user has a latin character in the surname, for example let’s say in the case of Gómez and Gracia, it puts Gracia before Gómez and it is because of the accent on the ó.

Is there any way I can interpret the accented ó and other latin chars as a regular o?
Many thanks!

Could you try followings please?

// sort by locale
->sortBy('lastname', 'asc', SORT_LOCALE_STRING);

// or this
->sortBy('lastname', 'asc', SORT_REGULAR);

Thanks for your quick reply @ahmetbora! but neither of both options works.

Hmm, SORT_LOCALE_STRING option works with locale, may be you need set locale with following option:

Yes I have 'locale' => 'es_ES.UTF-8' setted up correctly. But it seems it does not have any effect when using SORT_LOCALE_STRING

Then I have no idea about that. But last thing, I would just make sure that locale correctly set. For ex:

'locale' => ['es', 'es_ES', 'spanish', 'es_ES.UTF-8']

Thanks @ahmetbora, tried this on config.php and languages/es.php with SORT_LOCALE_STRING and SORT_REGULAR with no good news.

Is the locale actually installed? Like, put the following in a template and see what it outputs:

<pre><?= `locale -a` ?></pre>

The locales I have here on ubuntu, are written like "de_CH.utf8" and not "de_CH.UTF-8" (though I don’t know if that makes a difference).

If it isn’t installed but you have root rights on the server, you might want to install the “spanish language pack” for your distro (for “debiany” distros that would be something like apt-get update -y && apt-get install -y language-pack-es - then restart apache).

If it isn’t, but you can’t install it, or if it was but it’s not working, you might want to try writing a user method that transliterates the lastname to an ASCII version and then sort on that. This could be as simple as:

Kirby::plugin('my/plugin', [
    'userMethods' => [
        'translit_lastname' => function () {
            return Str::slug($this->lastname());
        }
    ]
]);

Then

$users = $kirby->users()->sortBy('translit_lastname');

Many thanks for your help @rasteiner, my locale output is OK.
Don’t know why your solution does not sort the users properly, but you give me an idea and I have it working with this code:

$users = $kirby->users()->sortBy(function($element) {
           return transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()',
           $element->lastname());
         });

Thanks for your support!

1 Like