Sort method: 1. Use the ksort() function to sort the array in ascending order according to the array key name. The syntax is "ksort(associative array, 0)"; 2. Use the krsort() function to sort the array according to the array key name. The key name sorts the array in descending order (from large to small, from high to low), the syntax is "krsort(associative array, 0);".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
How to sort php array by key 1 : Use ksort() function
ksort() function can sort the array in ascending order (from small to large, from low to high) according to the key name of the array. This function is mainly used for associative arrays. The syntax format is as follows:
ksort($array [, $sort_flags = SORT_REGULAR])
The parameter description is as follows:
$array: is the array to be sorted.
$sort_flags: is an optional parameter, used to define the mode of function sorting. The default value is "SORT_REGULAR". The value of $sort_flags is the same as the $sort_flags parameter in the sort() function.
Example:
1, 'g' => 2, 'a' => 3, 'd' => 4 ); echo ''; ksort($info, 0); print_r($info); ?>Copy after login
Output:
How to sort php array by key 2: Use the krsort() function
krsort() function can sort the array in descending order (from large to small, high to low) according to the key name of the array. This function is mainly used for associative arrays. The syntax format is as follows:
krsort($array [, $sort_flags = SORT_REGULAR])
The parameter description is as follows:
$array: is the array to be sorted.
$sort_flags: is an optional parameter, used to define the mode of function sorting. The default value is "SORT_REGULAR". The value of $sort_flags is the same as the $sort_flags parameter in the sort() function.
Example:
1, 'g' => 2, 'a' => 3, 'd' => 4 ); echo ''; krsort($info, 0); print_r($info); ?>Copy after login
Output:
PHP Video Tutorial》
The above is the detailed content of How to sort php array by key name. For more information, please follow other related articles on the PHP Chinese website!