PHP中array_multisort函数对多个数组或多维数组进行排序,参数数组被当成一个表的列并以行来排序——这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的大小来排序,依此类推。注意:作为参数的数组元素个数应保持一致,否则会报错。
先看一个对多个数组进行排序的例子。
- $array1 = array('one'=>'10','two'=>'20','three'=>'20','four'=>10);
- $array2 = array('one'=>'10','two'=>'30','three'=>'20','four'=>'1');
- $array3 = array('one'=>'C','two'=>'A','three'=>'B','four'=>'F');
- array_multisort($array1,$array2,$array3);
- print_r($array1);//Array ( [four] => 10 [one] => 10 [three] => 20 [two] => 20 )
- print_r($array2);//Array ( [four] => 1 [one] => 10 [three] => 20 [two] => 30 )
- print_r($array3);//Array ( [four] => F [one] => C [three] => B [two] => A )
在上面的例子中,首先对第一个参数数组进行排序(默认所有数组升序排序),我们可以看出第一个数组中存在相同的值(键名‘one’和‘four’的键值相同,键名‘two’和‘three’的键值相同),所以在排序第一个数组的相同值时就按照下一个输入数组中相应值的大小来排序(第二个数组‘four’的值小于‘one’的值,因此four的值排在one的前面),依此类推。
在看一个,改变排序顺序的例子。
- $array1 = array('one'=>'10','two'=>'20','three'=>'20','four'=>10);
- $array2 = array('one'=>'10','two'=>'30','three'=>'20','four'=>'1');
- $array3 = array('one'=>'C','two'=>'A','three'=>'B','four'=>'F');
- array_multisort($array1,SORT_DESC,$array2,SORT_ASC,$array3);
- print_r($array1);//Array ( [three] => 20 [two] => 20 [four] => 10 [one] => 10 )
- print_r($array2);//Array ( [three] => 20 [two] => 30 [four] => 1 [one] => 10 )
- print_r($array3);//Array ( [three] => B [two] => A [four] => F [one] => C )
注意:如果要是排序数组都是关联数组,则保留原有key名,若存在索引数组,则会按顺序重新建立索引。
- $array1 = array('one'=>'10',2=>'20',3=>'20',4=>10);
- $array2 = array('one'=>'10','2'=>'30','3'=>'20','four'=>'1');
- $array3 = array('one'=>'C','2'=>'A','3'=>'B','four'=>'F');
- array_multisort($array1,$array2,$array3);
- print_r($array1); //Array ( [0] => 10 [one] => 10 [1] => 20 [2] => 20 )
- print_r($array2); //Array ( [four] => 1 [one] => 10 [0] => 20 [1] => 30 )
- print_r($array3); //Array ( [four] => F [one] => C [0] => B [1] => A )
多维数组排序。
我们通常有一些多维数组需要排序:
- $guys = array(
- array('name'=>'jake', 'score'=>80, 'grade' =>'A'),
- array('name'=>'jina', 'score'=>70, 'grade'=>'A'),
- array('name'=>'john', 'score'=>70, 'grade' =>'A'),
- array('name'=>'ben', 'score'=>20, 'grade'=>'B')
- );
- //例如我们想按成绩倒序排列,如果成绩相同就按名字的升序排列。
- //这时我们就需要根据$guys的顺序多弄两个数组出来:
- $scores = array(80,70,70,20);
- $names = array('jake','jina','john','ben');
- //然后
- array_multisort($scores, SORT_DESC, $names, $guys);
- foreach($guys as $v){
- print_r($v);
- echo "<br/>";
- }
- /*
- Array ( [name] => jake [score] => 80 [grade] => A )
- Array ( [name] => jina [score] => 70 [grade] => A )
- Array ( [name] => john [score] => 70 [grade] => A )
- Array ( [name] => ben [score] => 20 [grade] => B )
- */