1.最简单的莫过于 sort,不过sort只支持索引数组的键值排序,不维系原本的键名--键值关系
<?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ?> 结果为: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
2.asort排序函数,维系键名 -- 键值关系,按键值排序
<?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> 结果为: c = apple b = banana d = lemon a = orange
3.ksort排序函数,维系键名 -- 键值关系,按键名排序
<?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> 结果为: a = orange b = banana c = apple d = lemon
4.array_multisort,排序多个数组,每个数组都是“列数组”,一个数组排序好了,另外的数组也会相应调整,类比数据库中的 order by 指定了多个字段进行排序,每个字段下面的数据类比这里的一个数组!
<?php $ar1 = array(10, 100, 100, 0); $ar2 = array(1, 3, 2, 4); array_multisort($ar1, $ar2); var_dump($ar1); var_dump($ar2); ?> 结果为: array(4) { [0]=> int(0) [1]=> int(10) [2]=> int(100) [3]=> int(100) } array(4) { [0]=> int(4) [1]=> int(1) [2]=> int(2) [3]=> int(3) }
5.usort,自定义排序函数
function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $a = array(3, 2, 5, 6, 1); usort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n"; } ?> 结果为: 0: 1 1: 2 2: 3 3: 5 4: 6
uasort,自定义排序函数,比较键值,仍然维系键名 -- 键值关系
<?php //自定义比较函数 function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } //原始数组 $array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4); print_r($array); //排序并输出结果 uasort($array, 'cmp'); print_r($array); ?> 结果为: Array ( [a] => 4 [b] => 8 [c] => -1 [d] => -9 [e] => 2 [f] => 5 [g] => 3 [h] => -4 ) Array ( [d] => -9 [h] => -4 [c] => -1 [e] => 2 [g] => 3 [a] => 4 [f] => 5 [b] => 8 )
uksort,自定义排序函数,比较键名,仍然维系键名 -- 键值关系
<?php function cmp($a, $b) { //去除掉前置的量词 $a = preg_replace('@^(a|an|the) @', '', $a); $b = preg_replace('@^(a|an|the) @', '', $b); //忽略大小写比较两个字符串 return strcasecmp($a, $b); } $a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4); uksort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value\n"; } ?> 结果为: an apple: 3 a banana: 4 the Earth: 2 John: 1