Home  >  Article  >  Backend Development  >  How to sort php array by key name

How to sort php array by key name

青灯夜游
青灯夜游Original
2021-06-24 18:02:125018browse

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])

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

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])

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

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!

Statement:
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