Fast array sorting method in PHP that preserves key names: use the ksort() function to sort the keys. Use the uasort() function to sort using a user-defined comparison function. Practical example: To sort an array of user IDs and scores by score while preserving the user ID, you can use the uasort() function and a custom comparison function.
Fast array sorting method in PHP that preserves key names
In PHP, array sorting usually scrambles key names. However, sometimes it is important to preserve the original key names. Listed below are several ways to quickly sort an array while preserving key names:
1. Use ksort()
ksort()
The function sorts the keys in the array and retains the original key names.
$arr = ['apple' => 5, 'banana' => 1, 'cherry' => 3]; ksort($arr); print_r($arr);
Output:
Array ( [apple] => 5 [banana] => 1 [cherry] => 3 )
2. Use uasort()
##uasort() function Sort an associative array using a user-defined comparison function while preserving key names.
function cmp($a, $b) { return $a <=> $b; } $arr = ['apple' => 5, 'banana' => 1, 'cherry' => 3]; uasort($arr, "cmp"); print_r($arr);
Array ( [banana] => 1 [cherry] => 3 [apple] => 5 )
Practical case
Suppose you have an array of user IDs and corresponding scores. You need to sort the array while preserving the user ID.$scores = [ 'user1' => 85, 'user2' => 90, 'user3' => 75, ]; // 使用 uasort() 排序数组 function cmp($a, $b) { return $a[1] <=> $b[1]; } uasort($scores, "cmp");
Array ( [user3] => 75 [user1] => 85 [user2] => 90 )
The above is the detailed content of Fast array sorting method that preserves key names in PHP. For more information, please follow other related articles on the PHP Chinese website!