Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a collection of UTF-8 strings containing non-Latin chars in Laravel 5.3?

Folks, I want to sort following nested collection by string alphabeticaly:

$collection = collect([
    ["name"=>"maroon"],
    ["name"=>"zoo"],
    ["name"=>"ábel"],
    ["name"=>"élof"]
])->sortBy("name");

I would expect:

1=> "ábel"
2=> "élof"
3=> "maroon"
4=> "zoo"

I got instead:

1=> "maroon"
2=> "zoo"
3=> "ábel"
4=> "élof"

I seen some PHP threads for this, but I am curious if there is any Laravel workaround for this. Thanks.

like image 546
Fusion Avatar asked Feb 06 '23 04:02

Fusion


2 Answers

Well, I had this problem and I was able to solve it like this:

$list = $Company->administrator->sortBy(function($adm){
   return iconv('UTF-8', 'ASCII//TRANSLIT', $adm->person->name);
});

My environment was Laravel 5.5 and PHP 7.1

like image 185
Romario Marinho Avatar answered Apr 27 '23 06:04

Romario Marinho


You don't need to use the Collator class in this case. Laravel's collection sortBy uses asort() and arsort() internally, which has the SORT_LOCALE_STRING flag for sorting according to the currently set locale.

So, your example can be written as follows:

setlocale(LC_COLLATE, 'fr_FR.utf8'); // No need to set this if you're doing it elsewhere

$collection = collect([
    ["name"=>"maroon"],
    ["name"=>"zoo"],
    ["name"=>"ábel"],
    ["name"=>"élof"]
])->sortBy("name", SORT_LOCALE_STRING); // Signals to arsort() to take locale into consideration

This also means you don't have to convert back-and-forth from a generic PHP array to a Laravel collection.

like image 32
DfKimera Avatar answered Apr 27 '23 07:04

DfKimera