数组的排序函数
1. 简单的数组排序sort() rsort()
$data=array(5,8,1,7,2);
sort($data);//元素由小到大进行排序
print_r($data);//Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 7 [4] => 8 )
rsort($data);//元素由大到小进行排序
print_r($data);//Array ( [0] => 8 [1] => 7 [2] => 5 [3] => 2 [4] => 1 )
2. 根据键名对数组排序 ksort() krsort()
$data=array(5=>"five",8=>"eight",1=>"one",7=>"seven",2=>"two");
ksort($data);//对数组的下标进行由小到大排序
print_r($data);//Array ( [1] => one [2] => two [5] => five [7] => seven [8] => eight )
krsort($data);//对数组的下标进行由大到小排序
print_r($data);//Array ( [8] => eight [7] => seven [5] => five [2] => two [1] => one
3. 根据元素的值对数组排序asort() arsort()
//根据元素的值对数组排序
$data=array("1"=>"Linux","a"=>"Apache","m"=>"MySQL","l"=>"PHP");
//asort() arsort 与 sort() rsort()的区别在于 前者排序后保持原有的键名,后者不保持原有键名,且键名从0开始
asort($data);
print_r($data);//Array ( [a] => Apache [1] => Linux [m] => MySQL [l] => PHP )
arsort($data);
print_r($data);//Array ( [l] => PHP [m] => MySQL [1] => Linux [a] => Apache )
sort($data);
print_r($data);//Array ( [0] => Apache [1] => Linux [2] => MySQL [3] => PHP )
rsort($data);
print_r($data);//Array ( [0] => PHP [1] => MySQL [2] => Linux [3] => Apache )
4.根据"自然数排序“法对数组排序natsort()
区分大小写字母比较 natcasescort()//不区分大小写字母的比较
//根据”自然数排序法“对数组排序(0-9短者优先)
$data=array("file.txt","file11.txt","file2.txt","file22.txt");
sort($data);
print_r($data);//Array ( [0] => file.txt [1] => file11.txt [2] => file2.txt [3] => file22.txt )
natsort($data);
print_r($data);//Array ( [0] => file.txt [2] => file2.txt [1] => file11.txt [3] => file22.txt )
natcasesort($data);
print_r($data);//Array ( [0] => file.txt [2] => file2.txt [1] => file11.txt [3] => file22.txt )
5.根据用户自定义规则对数组排序 usort() uasort() uksort()对键排序
//用户自定义排序函数
$data=array("Linux","Apache","MySQL","PHP");
usort($data,"sortbylen");//通过元素长度排序
print_r($data);//Array ( [0] => PHP [1] => MySQL [2] => Linux [3] => Apache )
function sortbylen($one,$two){
if(strlen($one)==strlen($two))
return 0;
else
return (strlen($one)>strlen($two))?1:-1;
}
已有 0 条评论