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:
<?php $info = array( 'b' => 1, 'g' => 2, 'a' => 3, 'd' => 4 ); echo '<pre class="brush:php;toolbar:false">'; ksort($info, 0); print_r($info); ?>
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:
<?php $info = array( 'b' => 1, 'g' => 2, 'a' => 3, 'd' => 4 ); echo '<pre class="brush:php;toolbar:false">'; krsort($info, 0); print_r($info); ?>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
