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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With