PHP排序数组


PHP排序数组

PHP提供了几种排序数组的函数。本页介绍了不同的功能并包含了示例。

sort()

sort()函数按升序字母/数字顺序对数组的值进行排序(例如A,B,C,D,E ... 5,4,3,2,1 ...)

<?php
 $codingdict = array("free", "code", "camp");
 sort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [0] => camp
    [1] => code
    [2] => free
 )

rsort()

rsort()函数按降序字母/数字顺序对数组的值进行排序(例如Z,Y,X,W,V ... rsort() ......)

<?php
 $codingdict = array("free", "code", "camp");
 rsort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [0] => free
    [1] => code
    [2] => camp
 )

ASORT()

asort()函数按字母顺序/数字顺序(例如A,B,C,D,E ... 5,4,3,2,1 ......)对其关联数组进行排序。

<?php
 $codingdict = array("zero"=>"free", "one"=>"code", "two"=>"camp");
 asort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [two] => camp
    [one] => code
    [zero] => free
 )

ksort()

ksort()函数按字母/数字顺序按字母顺序排列关联数组(例如A,B,C,D,E ... 5,4,3,2,1 ......)

<?php
 $codingdict = array("zero"=>"free", "one"=>"code", "two"=>"camp");
 ksort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [one] => code
    [two] => camp
    [zero] => free
 )

arsort()

arsort()函数按字母/数字顺序按字母顺序排列一个关联数组(例如Z,Y,X,W,V ... 5,4,3,2,1 ......)

<?php
 $codingdict = array("zero"=>"free", "one"=>"code", "two"=>"camp");
 arsort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [zero] => free
    [one] => code
    [two] => camp
 )

krsort()

krsort()函数按字母/数字顺序降序排序关联数组(例如Z,Y,X,W,V ... krsort() ......)

<?php
 $codingdict = array("zero"=>"free", "one"=>"code", "two"=>"camp");
 krsort($codingdict);
 print_r($codingdict);

输出:

Array
 (
    [zero] => free
    [two] => camp
    [one] => code
 )

更多PHP教程

学习更多PHP教程