note 129697 added to function.usort
| From: | rh@20i.com | Date: | Fri, 09 Aug 2024 13:25:36 +0000 |
| Subject: | note 129697 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221469@lists.php.net to get a copy of this message | ||
A sort function to sort elements by a reference order.
function sort_by_reference(array $array_to_sort, array $reference_array): array {
usort($array_to_sort, function($a, $b) use ($reference_array) {
$pos_a = array_search($a, $reference_array);
$pos_b = array_search($b, $reference_array);
return $pos_a - $pos_b;
});
return $array_to_sort;
}
// Example usage
$reference_array = ["one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten"];
$array_to_sort = ["three", "one", "seven", "four",
"ten"];
$sorted_array = sort_by_reference($array_to_sort, $reference_array);
// Print the result to verify the sorting
print_r($sorted_array);
```
Array
(
[0] => one
[1] => three
[2] => four
[3] => seven
[4] => ten
)
```
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 185.146.164.254)
----
Manual Page -- https://php.net/manual/en/function.usort.php
Edit -- https://main.php.net/note/edit/129697
Del: integrated -- https://main.php.net/note/delete/129697/integrated
Del: useless -- https://main.php.net/note/delete/129697/useless
Del: bad code -- https://main.php.net/note/delete/129697/bad+code
Del: spam -- https://main.php.net/note/delete/129697/spam
Del: non-english -- https://main.php.net/note/delete/129697/non-english
Del: in docs -- https://main.php.net/note/delete/129697/in+docs
Del: other reasons-- https://main.php.net/note/delete/129697
Reject -- https://main.php.net/note/reject/129697
Search -- https://main.php.net/manage/user-notes.php