PHP 二维数组排序
1 sort()和rsort()
1.1 sort()
- 函数对数组根据值进行升序排序;
- 为数组中的单元赋予新的键名,原有的键名将被删除;
- 如果成功则返回 TRUE,否则返回 FALSE;
$cars=array('a'=>"Volvo",2=>"BMW",'b'=>"Ford",6=>"Chevrolet",5=>"MG");
sort($cars);
var_dump($cars);
array(5) {
[0]=>
string(3) "BMW"
[1]=>
string(9) "Chevrolet"
[2]=>
string(4) "Ford"
[3]=>
string(2) "MG"
[4]=>
string(5) "Volvo"
}
1.2 rsort()
- 对数组根据值进行降序排序;
- 为数组中的单元赋予新的键名,原有的键名将被删除;
- 如果成功则返回 TRUE,否则返回 FALSE;
$cars=array('a'=>"Volvo",2=>"BMW",'b'=>"Ford",6=>"Chevrolet",5=>"MG");
rsort($cars);
var_dump($cars);
array(5) {
[0]=>
string(5) "Volvo"
[1]=>
string(2) "MG"
[2]=>
string(4) "Ford"
[3]=>
string(9) "Chevrolet"
[4]=>
string(3) "BMW"
}
2 asort()和arsort()
2.1 asort()
- 函数对数组根据值进行升序排序;
- 原有对应的键名不变;
- 如果成功则返回 TRUE,否则返回 FALSE;
$age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43", "Mike"=>'30', "Peak"=>"28");
asort($age);
var_dump($age);
array(5) {
["Peak"]=>
string(2) "28"
["Mike"]=>
string(2) "30"
["Bill"]=>
string(2) "35"
["Steve"]=>
string(2) "37"
["Peter"]=>
string(2) "43"
}
2.2 arsort()
- 函数对数组根据值进行降序排序;
- 原有对应的键名不变;
- 如果成功则返回 TRUE,否则返回 FALSE;
$age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43", "Mike"=>'30', "Peak"=>"28");
arsort($age);
var_dump($age);
array(5) {
["Peter"]=>
string(2) "43"
["Steve"]=>
string(2) "37"
["Bill"]=>
string(2) "35"
["Mike"]=>
string(2) "30"
["Peak"]=>
string(2) "28"
}
3 ksort()和krsort()
3.1 ksort()
- 函数对数组根据键进行升序排序;
- 原有对应的键名和值不变;
- 如果成功则返回 TRUE,否则返回 FALSE;
$age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43", "Mike"=>'30', "Peak"=>"28");
ksort($age);
var_dump($age);
array(5) {
["Bill"]=>
string(2) "35"
["Mike"]=>
string(2) "30"
["Peak"]=>
string(2) "28"
["Peter"]=>
string(2) "43"
["Steve"]=>
string(2) "37"
}
3.2 krsort()
- 函数对数组根据键进行降序排序;
- 原有对应的键名和值不变;
- 如果成功则返回 TRUE,否则返回 FALSE;
$age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43", "Mike"=>'30', "Peak"=>"28");
krsort($age);
var_dump($age);
array(5) {
["Steve"]=>
string(2) "37"
["Peter"]=>
string(2) "43"
["Peak"]=>
string(2) "28"
["Mike"]=>
string(2) "30"
["Bill"]=>
string(2) "35"
}