php数组排序
- sort() - 以升序对数组排序
- rsort() - 以降序对数组排序
- asort() - 根据值,以升序对关联数组进行排序
- arsort() - 根据值,以降序对关联数组进行排序
- ksort() - 根据键,以升序对关联数组进行排序
- krsort() - 根据键,以降序对关联数组进行排序
以sort为例
<?php
$colors = array("red" => "b1","green" => "c2","blue" => "d3","yellow" => "a4");
var_dump($colors);
sort($colors);
var_dump($colors);
?>
执行结果如下
array(4) {
["red"]=>
string(2) "b1"
["green"]=>
string(2) "c2"
["blue"]=>
string(2) "d3"
["yellow"]=>
string(2) "a4"
}
array(4) {
[0]=>
string(2) "a4"
[1]=>
string(2) "b1"
[2]=>
string(2) "c2"
[3]=>
string(2) "d3"
}
即 sort和rsort在进行数组排序时根据数组的value,按照字母表a~z的顺序进行排序 ,排序后的数组的key值会强制变为0,1,2,3... ,原数组value不全为字母时,sort以及rsort会从第一位开始往后寻找字母进行排序,如若原数组的value不含a~z 如下
<?php
$colors = array("red" => "4","green" => "2","blue" => "3","yellow" => "1");
var_dump($colors);
sort($colors);
var_dump($colors);
?>
执行结果
array(4) {
["red"]=>
string(1) "4"
["green"]=>
string(1) "2"
["blue"]=>
string(1) "3"
["yellow"]=>
string(1) "1"
}
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
}
sort和rsort会按照数字的大小进行排序 key值也会强制转换成0,1,2,3.....
asort和arsort
根据value进行升序/降序,看起来跟sort和rsort一样,但是sort和rsort的排序会重置原先的key值,变成0,1,2,3...,而asort和arsort并不会 其他规则一样 如下
<?php
$colors = array("red" => "4","green" => "2","blue" => "3","yellow" => "1");
var_dump($colors);
asort($colors);
var_dump($colors);
?>
执行结果
array(4) {
["red"]=>
string(1) "4"
["green"]=>
string(1) "2"
["blue"]=>
string(1) "3"
["yellow"]=>
string(1) "1"
}
array(4) {
["yellow"]=>
string(1) "1"
["green"]=>
string(1) "2"
["blue"]=>
string(1) "3"
["red"]=>
string(1) "4"
}
ksort以及krsrot示例
<?php
$colors = array("red" => "4","green" => "2","blue" => "3","yellow" => "1");
var_dump($colors);
ksort($colors);
var_dump($colors);
?>
执行结果
array(4) {
["red"]=>
string(1) "4"
["green"]=>
string(1) "2"
["blue"]=>
string(1) "3"
["yellow"]=>
string(1) "1"
}
array(4) {
["blue"]=>
string(1) "3"
["green"]=>
string(1) "2"
["red"]=>
string(1) "4"
["yellow"]=>
string(1) "1"
}
网友评论