I'm trying to sort a list of email accounts by alphabetical order using Collection::sortBy() in cakephp 4, but it seems not working the way I use it.
$accounts = [
[
'email' => '[email protected]',
'isBlocked' => false,
],
[
'email' => '[email protected]',
'isBlocked' => false,
],
[
'email' => '[email protected]',
'isBlocked' => false,
],
[
'email' => '[email protected]',
'isBlocked' => false,
],
[
'email' => '[email protected]',
'isBlocked' => false,
]
];
$sorted = collection($accounts)
->sortBy('email', SORT_ASC)
->toArray();
debug($sorted);
debug($sorted) returns exactly the same array as $accounts...
What am I doing wrong ?
CodePudding user response:
The default sort type is SORT_NUMERIC, and converted to numbers, all your strings will be 0, hence all are equal as seen by the sorting mechanism, and nothing will chance.
For strings use SORT_NATURAL, SORT_STRING, SORT_LOCALE_STRING, or SORT_REGULAR, eg:
sortBy('email', SORT_ASC, SORT_NATURAL)
The Cookbook needs a fix there I think, as it shows referencing string fields without specifying the required sort type.
See also
