-
Notifications
You must be signed in to change notification settings - Fork 5
FR: Locale base string comparison for collection sort #1574
Comments
Nice work 👍 |
Can you give me an example of a list of titles/words and how they should be sorted in a particular language? |
Sure... given this list of Danish cities in a random order:
This is the natural sort in Danish:
ÆØÅ is the last 3 letters in Danish, and Å is the new way of writing Aa, though cities use the old way. |
Thanks! |
Just for those who is still waiting for the feature but does not want to modify core files: here is my code for a custom modifier that does the sorting right: public function index($value, $params, $context)
{
$originalCollateLocale = setlocale(LC_COLLATE, 0);
$currentCollateLocale = Config::getFullLocale();
$key = array_get($params, 0);
$is_descending = strtolower(array_get($params, 1)) == 'desc';
if ($key === 'random') {
return $this->shuffle($value);
}
// Using sort="true" will allow primitive arrays to be sorted.
if ($key === 'true') {
natcasesort($value);
return $is_descending ? $this->reverse($value) : $value;
}
setlocale(LC_COLLATE, $currentCollateLocale);
$return = collect($value)->sortBy($key, SORT_LOCALE_STRING, $is_descending)->values()->toArray();
setlocale(LC_COLLATE, $originalCollateLocale);
return $return;
} Please make sure to set full locale name in locales:
de:
full: de_CH.utf8
... Also I had a problem with testing the code because in my local setup (MacOS/AMPPS) some locale-related modules are missing. Still no idea how to solve it. Works as expected on the hosting. P.s. I'm not sure if it was a mauvais ton to write into a closed issue, please correct me. |
It was added in September 2017. What's not working? |
Ah, now I see where the confusion comes from. The original claim was about collection sorting and I am talking about Original # $options = SORT_REGULAR
$descending ? arsort($results, $options) : asort($results, $options); And That's why I came to idea of the plugin. |
Default behaviour of collection sort is to use
strcasecmp()
, which is great for English but bad for every other language.This changes the default to use the Collator class if the Intl extension is present, or use current behaviour as fallback.
In Statamic\API\Helper change line 341 from:
To:
In Statamic\API\Str add the following code:
All you then need to do is set the current locale and ensure the Intl extension is installed.
The text was updated successfully, but these errors were encountered: