note 119343 added to function.array-multisort
| From: | faugeron dot loic at gmail dot com | Date: | Tue, 17 May 2016 07:14:56 +0000 |
| Subject: | note 119343 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205497@lists.php.net to get a copy of this message | ||
Improving Example #3 (Sorting database results): using <?php array_column ?> (PHP >= 5.5)
and <?php call_user_func_array ?> it becomes possible to build your sortings (sorting by one
or many fields):
<?php
$data = [
[
'id' => '168ac7f8-c918-4e99-90ee-5d7590fe61ce',
'name' => 'Arthur Dent',
],
[
'id' => 'e3ad45ee-7cae-4cca-bd7b-2eb6b57b6457',
'name' => 'Ford Prefect',
],
[
'id' => 'a426aef2-19e2-412a-8339-5458cf6ae416',
'name' => 'Trillian Astra',
],
];
$sortings = [
[
'field' => 'id',
'direction' => SORT_DESC,
],
];
$args = [];
$key = 0;
foreach ($sortings as $sorting) {
$args[$key] = array_column($data, $sorting['field']);
$args[$key + 1] = $sorting['direction'];
$key += 2;
}
$args[] = $data;
call_user_func_array('array_multisort', $args);
// $data is now sorted by ID in descending order.
?>
----
Server IP: 72.52.91.14
Probable Submitter: 85.255.232.184
----
Manual Page -- http://php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/119343
Del: integrated -- https://master.php.net/note/delete/119343/integrated
Del: useless -- https://master.php.net/note/delete/119343/useless
Del: bad code -- https://master.php.net/note/delete/119343/bad+code
Del: spam -- https://master.php.net/note/delete/119343/spam
Del: non-english -- https://master.php.net/note/delete/119343/non-english
Del: in docs -- https://master.php.net/note/delete/119343/in+docs
Del: other reasons-- https://master.php.net/note/delete/119343
Reject -- https://master.php.net/note/reject/119343
Search -- https://master.php.net/manage/user-notes.php