php array_multisort 对数组进行排序详解及实例代码
php中array_multisort()函数可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。本文章向大家讲解array_multisort函数的使用方法。
array_multisort()函数返回排序数组。您可以输入一个或多个数组。函数先对第一个数组进行排序,接着是其他数组,如果两个或多个值相同,它将对下一个数组进行排序。
注释:字符串键名将被保留,但是数字键名将被重新索引,从0开始,并以1递增。
注释:您可以在每个数组后设置排序顺序和排序类型参数。如果没有设置,每个数组参数会使用默认值。
语法
array_multisort(array1,sortingorder,sortingtype,array2,array3...)
参数描述
可选。规定排列顺序。可能的值: 可选。规定排序类型。可能的值:
参数
描述
array1
必需。要排序的一个。
sortingorder
sortingtype
array2
可选。规定数组。
array3
可选。规定数组。
返回值
成功时返回TRUE,或者在失败时返回FALSE。
说明
array_multisort()函数对多个数组或多维数组进行排序。
参数中的数组被当成一个表的列并以行来进行排序-这类似SQL的ORDERBY子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话,就会按照下一个输入数组中相应值的大小进行排序,依此类推。
第一个参数是数组,随后的每一个参数可能是数组,也可能是下面的排序顺序标志(排序标志用于更改默认的排列顺序)之一:
SORT_ASC-默认,按升序排列。(A-Z)
SORT_DESC-按降序排列。(Z-A)
随后可以指定排序的类型:
SORT_REGULAR-默认。将每一项按常规顺序排列。
SORT_NUMERIC-将每一项按数字顺序排列。
SORT_STRING-将每一项按字母顺序排列。
实例一:
排序多维数组
<?php $ar=array( array("10",11,100,100,"a"), array(1,2,"2",3,1) ); array_multisort($ar[0],SORT_ASC,SORT_STRING,$ar[1],SORT_NUMERIC,SORT_DESC); var_dump($ar); ?>
本例中在排序后,第一个数组将变成"10",100,100,11,"a"(被当作字符串以升序排列)。第二个数组将包含1,3,"2",2,1(被当作数字以降序排列)。
运行结果:
array(2){ [0]=>array(5){ [0]=>string(2)"10" [1]=>int(100) [2]=>int(100) [3]=>int(11) [4]=>string(1)"a" } [1]=>array(5){ [0]=>int(1) [1]=>int(3) [2]=>string(1)"2" [3]=>int(2) [4]=>int(1) } }
实例二:
不区分大小写字母排序
SORT_STRING和SORT_REGULAR都是区分大小写字母的,大写字母会排在小写字母之前。
要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。
<?php $array=array('Alpha','atomic','Beta','bank'); $array_lowercase=array_map('strtolower',$array); array_multisort($array_lowercase,SORT_ASC,SORT_STRING,$array); print_r($array); ?>
运行结果:
Array ( [0]=>Alpha [1]=>atomic [2]=>bank [3]=>Beta )
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!