先介绍下php中用于数组排序的函数:
排序方法 升序 降序 用户自定义顺序
键排序 ksort() krsort() uksort()
值排序不改变键值 asort() arsort() uasort()
值排序改变键值 sort() rsort() usort()
分享一个php数组排序的例子:
<?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> ";
}
?>
$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> ";
}
?>
输出结果:
a = aliceblue
b = blue
g = gold
y = yellow
下面的是一个用户自定义的排序:
<?php
function cmp($a, $b){
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 :1;
} // www.jbxue.com
$a = array(4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
uksort($a, "cmp");
while (list($key, $val) = each($a)) {
echo "$key = $val<br> ";
}
?>
function cmp($a, $b){
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 :1;
} // www.jbxue.com
$a = array(4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
uksort($a, "cmp");
while (list($key, $val) = each($a)) {
echo "$key = $val<br> ";
}
?>
输出结果:
20 = twenty
10 = ten
4 = four
3 = three
uksort()是用户按键排序的,我们定义了键为number类型,在cmp()函数中进行降序排列。