note 118150 deleted from function.uksort by cmb
| From: | cmb@php.net | Date: | Sat, 27 Aug 2016 18:32:31 +0000 |
| Subject: | note 118150 deleted from function.uksort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206404@lists.php.net to get a copy of this message | ||
Note Submitter: thiago at internetbudi dot com dot br
----
Sort the indices by a set order (custom order)
<?php
function sort_keys(&$array, $order) {
uksort($array, function ($a, $b) use ($order) {
$pos_a = array_search($a, $order);
$pos_b = array_search($b, $order);
if ($pos_a === false)
return 1;
if ($pos_b === false)
return -1;
return $pos_a - $pos_b;
});
return $array;
}
$order = ['a', 'c', 'z'];
$arr = ['a'=>1, 'b'=>2, 'c'=>3, 'f'=>4,
'z'=>5];
sort_keys($arr, $order);
// => [
// "a" => 1,
// "c" => 3,
// "z" => 5,
// "b" => 2,
// "f" => 4
// ]