Home >Backend Development >PHP Tutorial >How to sort an array based on a specific key-value pair using PHP, preserving the original key names?
Use the PHP uasort function and provide a comparison function to sort the array according to the specific key values in the array while retaining the original key names. The specific steps are as follows: define a comparison function that accepts two key-value pairs as parameters and returns an integer; call the uasort function and pass in the array to be sorted and the comparison function; the sorted array will retain the original key names.
#How to use PHP to sort according to a specific key-value pair in an array, retaining the original key name?
In PHP, use the uasort
function to sort according to a specific key-value pair in the array while retaining the original key name. Here is its syntax:
uasort(array $array, callable $value_compare_func)
Where:
array
The array to sort value_compare_func
A comparison Function, which will be used to compare two key-value pairs in the arrayThe comparison function should accept two parameters (the key-value pairs of the two elements in the array) and return an integer:
Practical case
Suppose we have an array named $data
which contains student information and their grades:
$data = [ 'John Doe' => 85, 'Jane Smith' => 90, 'Bob Jones' => 75 ];
We can use the following code to sort the array based on grades, While retaining the original key names:
uasort($data, function($a, $b) { return $a - $b; });
The sorted array will look like this:
print_r($data); // 输出: // Array // ( // [Jane Smith] => 90 // [John Doe] => 85 // [Bob Jones] => 75 // )
The above is the detailed content of How to sort an array based on a specific key-value pair using PHP, preserving the original key names?. For more information, please follow other related articles on the PHP Chinese website!