note 128210 added to function.array-multisort
| From: | Sbastien at main dot php dot net | Date: | Sat, 11 Feb 2023 21:33:27 +0000 |
| Subject: | note 128210 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220165@lists.php.net to get a copy of this message | ||
The shuttle operator can be a smart alternative to array_multisort() for multidimensional and/or
custom sorting.
<?php
$data = [
['name' => 'John Smith', 'status' => 'Offline'],
['name' => 'Anne Onyme', 'status' => 'Online'],
['name' => 'Alan Smithee', 'status' => 'Online'],
];
// Online first, then alphabetic name order
usort($data, fn ($a, $b) => [
['Online' => 1, 'Offline' => 2][$a['status']],
$a['name'],
] <=> [
['Online' => 1, 'Offline' => 2][$b['status']],
$b['name'],
]);
print_r($data);
/*
Array
[0] => Array
[name] => Alan Smithee
[status] => Online
[1] => Array
[name] => Anne Onyme
[status] => Online
[2] => Array
[name] => John Smith
[status] => Offline
*/
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.130 (proxied: 2a01:e0a:968:1840:f155:50cc:aa62:fa44)
----
Manual Page -- https://php.net/manual/en/function.array-multisort.php
Edit -- https://main.php.net/note/edit/128210
Del: integrated -- https://main.php.net/note/delete/128210/integrated
Del: useless -- https://main.php.net/note/delete/128210/useless
Del: bad code -- https://main.php.net/note/delete/128210/bad+code
Del: spam -- https://main.php.net/note/delete/128210/spam
Del: non-english -- https://main.php.net/note/delete/128210/non-english
Del: in docs -- https://main.php.net/note/delete/128210/in+docs
Del: other reasons-- https://main.php.net/note/delete/128210
Reject -- https://main.php.net/note/reject/128210
Search -- https://main.php.net/manage/user-notes.php