本篇文章是对PHP数组排序函数合集以及它们之间的联系进行了详细的分析介绍,需要的朋友参考下
下边提到的几个数组函数的排序有一些共性:
复制代码 代码如下:
bool sort ( array &$array [, int $sort_flags= SORT_REGULAR ] )
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
var_dump($fruits);
?>
结果:
array
0 =>
string
'apple' (length=5)
1 =>
string
'banana' (length=6)
2 =>
string
'lemon' (length=5)
3 =>
string
'orange' (length=6)
复制代码 代码如下:
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
var_dump($fruits);
?>
结果:
array
0 =>
string
'orange' (length=6)
1 =>
string
'lemon' (length=5)
2 =>
string
'banana' (length=6)
3 =>
string
'apple' (length=5)
复制代码 代码如下:
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
var_dump($fruits);
?>
结果:
array
'c' =>
string
'apple' (length=5)
'b' =>
string
'banana' (length=6)
'd' =>
string
'lemon' (length=5)
'a' =>
string
'orange' (length=6)
复制代码 代码如下:
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
var_dump($fruits);
?>
结果
array
'a' =>
string
'orange' (length=6)
'd' =>
string
'lemon' (length=5)
'b' =>
string
'banana' (length=6)
'c' =>
string
'apple' (length=5)
复制代码 代码如下:
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
var_dump($fruits);
?>
结果
array
'a' =>
string
'orange' (length=6)
'b' =>
string
'banana' (length=6)
'c' =>
string
'apple' (length=5)
'd' =>
string
'lemon' (length=5)
复制代码 代码如下:
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
var_dump($fruits);
?>
array
'd' =>
string
'lemon' (length=5)
'c' =>
string
'apple' (length=5)
'b' =>
string
'banana' (length=6)
'a' =>
string
'orange' (length=6)
复制代码 代码如下:
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a }
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
var_dump($a);
?>
复制代码 代码如下:
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");
var_dump($a);
?>
复制代码 代码如下:
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a }
// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
var_dump($array);
// Sort and print the resulting array
uasort($array, 'cmp');
var_dump($array);
?>
复制代码 代码如下: