How to sort php array by key name

青灯夜游
Release: 2023-03-10 21:20:02
Original
4912 people have browsed it

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);".

How to sort php array by key name

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])
Copy after login

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 name

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])
Copy after login

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:

How to sort php array by key name

##Recommended learning: "

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!