PHP has a lot of built-in sorting functions, pros and cons of various rows;
Commonly used sorting functions:
Sort ()-sorts an array in ascending order
Rsort ()-sorts the array in descending order
Asort ()-sorts associative arrays in ascending order based on values
Ksort ()-Sorts the associative array in ascending order, based on the key
Arsort ()-sorts associative arrays in descending order by value
Krsort ()-Sorts the associative array in descending order, based on the key
Basic can meet the needs of the use of these functions are not more verbose;
But in the actual development of the project there will be some more demanding sorting requirements; the sort function to be introduced today is: Uasort ()
Uasort is mainly used in the order of the multidimensional arrays that need to follow the custom method and keep the index relationship ;
Has the following array
$sort _array = array ( "Array1" => array ( ' word ' = ' test1 ', ' Sortnumber ' =>1, ), ' Array3 ' =>array ( ' word ' = ' test4 ', ' Sortnumber ' =>4, ), ' array2 ' =>array ( ' word ' ~ = ' test3 ', ' Sortnumber ' =>3, ), ' Array5 ' =>array ( ' word ' = ' test5 ', ), ' Array4 ' =>array ( ' word ' = ' test2 ', ' Sortnumber ' =>2, ),);
The requirements are sorted in ascending order according to Sortnumber;
First, you need to write a custom sort rule;
Custom sort functions Function My_sort ($a, $b) {$prev = isset ($a [' sortnumber '])? $a [' Sortnumber ']: 0; $next = Isset ($b [' Sortnumber '])? $b [' Sortnumber ']: 0; if ($prev = = $next) return 0; Return ($prev < $next)? -1:1;} Echo ' <pre> sort before:<br> ';p rint_r ($sort _array); Uasort ($sort _array, "My_sort"); echo "Sort:<br>";p Rint_ R ($sort _array);
The results obtained:
Before sorting: Array ( [array1] => Array ( [word] => test1 [sortnumber] => 1 ) [array3] => Array ( [ Word] => test4 [sortnumber ] => 4 ) [array2] = > Array ( [word] => test3 [sortnumber] => 3 ) [array5] => array ( [word] => test5 ) [array4] => Array ( [word] => test2 [sortnumber] => 2 )) After sorting: Array ( [array5] => Array ( [ word] => test5 ) [array1] => array ( [word] => test1 [ sortnumber] => 1 ) [array4] => Array ( [word] => test2 [sortnumber] => 2 ) [array2] => Array ( [word] => test3 [sortnumber] => 3 ) [array3] => Array ( [word] => test4 [sortnumber] => 4 ))
The last to be reminded is: the custom function to use isset detection under the need to sort the existence of the field if there is no default 0 assigned to, otherwise there will be an error message;
650) this.width=650, "alt=" Bai Jun Remote Blog "src=" http://www.baijunyao.com/Upload/image/ueditor/20150725/1437837423120863. PNG "title=" Bai Jun Haruka Blog "/>
PHP multidimensional Array custom sort Uasort ()