四、数组的排序函数
sort(&$arr [,$sort_type]) 对数组进行排序,并且改变键值,不敢原来是什么类型的数组,排序后的数组均为索引数组,第二个单词为排序的方式,比如是按字符串排序、还是数组等。一般很少使用。排序方式为升序
rsort(&$arr [,$sort_type]) 和sort一样,只不过排序方式为降序
<?php
$arr = array('one','two','three','four','five','six','num'=>'seven');
sort($arr);
echo "<pre>";
print_r($arr);
//结果为:
$arr = Array(
[0] => 'five',
[1] => 'four',
[2] => 'one',
[3] => 'seven',
[4] => 'six',
[5] => 'three',
[6] => 'two',
);
$arr = array('one','two','three','four','five','six','num'=>'seven');
rsort($arr);
echo "<pre>";
print_r($arr);
//结果为:
$arr = Array
(
[0] => 'two',
[1] => 'three',
[2] => 'six',
[3] => 'seven',
[4] => 'one',
[5] => 'four',
[6] => 'five'
);
usort(&$arr,callback)使用用户自定义的方式对数组进行排序,排序方式为升序
ursort(&$arr,callback)和usort差别就是排序方式为降序
$arr = array(5,-3,-7,1,9,4,2);
function fun($a,$b){
$a = abs($a);
$b = abs($b);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($arr,'fun');
echo "<pre>";
print_r($arr);
//输出的结果为
$arr = Array
(
[0] => 1,
[1] => 2,
[2] => -3,
[3] => 4,
[4] => 5,
[5] => -7,
[6] => 9,
)
asort(&$arr [,$sort_type]) 对数组进行排序并保持索引关系,升序
arsort(&$arr [,$sort_type]) 降序
$arr = array('one','two','three','four','five','six','num'=>'seven');
asort($arr);
echo "<pre>";
print_r($arr);
//输出结果为
$arr = Array
(
[4] => 'five',
[3] => 'four',
[0] => 'one',
['num'] => 'seven',
[5] => 'six',
[2] => 'three',
[1] => 'two',
);
ksort(&$arr [,$sort_type]) 对数组按键名进行排序,主要用与关联数组
krsort(&$arr [,$sort_type]) 降序
$arr = array('c'=>'one','d'=>'two','a'=>'three','b'=>'four');
ksort($arr);
echo "<pre>";
print_r($arr);
//输出结果为
$arr = Array
(
['a'] => 'three',
['b'] => 'four',
['c'] => 'one',
['d'] => 'two',
)
uasort(&$arr,callback) 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
uksort(&$arr,callback) 使用用户自定义的比较函数对数组中的键名进行排序
此函数和上面函数类似,不再举例