PHP中数组排序

排序方法                           升序                             降序                           用户自定义顺序
键排序                             ksort()                           krsort()                       uksort()
值排序不改变键值             asort()                           arsort()                       uasort()
值排序改变键值                 sort()                             rsort()                         usort()

下面是一个排序的例子:

<?php
   $color_arr = array("b" => "blue", "a" => "aliceblue", "g" => "gold", "y" => "yellow");
   ksort($color_arr);
   reset($color_arr);
   while (list($key, $val) = each($color_arr)) {
     echo "$key = $val<br>\n";
   }
?>

 

输出结果:

 

a = aliceblue
b = blue
g = gold
y = yellow

 

下面的是一个用户自定义的排序:

 

<?php
   function cmp($a, $b){
     if ($a == $b) {
       return 0;
     }
     return ($a > $b) ? -1 :1;
   }
   $a = array(4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
   uksort($a, "cmp");
   while (list($key, $val) = each($a)) {
     echo "$key = $val<br>\n";
   }
?>

 

输出结果:

 

20 = twenty
10 = ten
4 = four
3 = three

 

uksort()是用户按键排序的,我们定义了键为number类型,在cmp()函数中进行降序排列。

本文永久地址:https://sjolzy.cn/PHP-sort-array.html

--EOF--

标签: php, 排序

随机文章

添加新评论