sort()
Function and rsort()
Function: Grammar rules:
bool sort(array &array [,int sort_flags] bool rsort(array &array [.int_sort_flags]
Parameters:
The first parameter is a sorted array object
The second parameter is an optional value that can be selected:
SORT_REGULAR: It is the default value and will automatically Identify the element type of the array for sorting
SORT_NUMERIC: used for sorting array elements
SORT_STRING: used for string sorting
SORT_LOCALE_STRING: Compare elements as strings according to the current locale setting
Example:
$a=array(4,7,9,1); sort($a); pirnt_r($a); rsort($a); print_r($a);
Definition: ksort()
The function sorts the array from small to large according to the key name. krsort()
Contrary to the ksort()
function, the original keys are maintained for the array values after sorting.
Example
$data= array(5=>"five",8=>"eight",1=>"one",7=>"seven"); ksrot($data); print_r($data); krsot($data); print_r($data);
Definition: asort()
From small to large/ arsort()
From large to small, use this function to sort, the original key name will be ignored, use the sequential number to re-index the array subscript
Example:
$data=array("a"=>1,"b"=>2,"c"=>3); asort($data); print_r($data); arsort($data); print_r($data);
Definition : is a very special sorting method that uses cognition instead of calculation rules. This feature is called natural sorting method, that is, numbers from 1 to 9, letters from a-z, and the shorter one is given priority.
Example:
$data=array("file1.txt","file11.txt","file111.txt"); natsort($data);//普通自然排序 natcasesort($data);//忽略大小写
Grammar rules:
bool usort(array &array ,callback cmp_function) bool uasort(array &array,callback cmp_function) bool uksort(array &array,callback cmp_function)
Description: Custom callback function requires two parameters , respectively two consecutive elements of the array. Comparing the first parameter is less than, greater than, and equal to the second parameter returns 0, 1, -1 respectively
Example:
$data= array("ab","abc","a","ac","abcd"); usrot($data,"mysortByLen"); function mysortByLen($one,$two){ if(strlen($one)== strlen($two)){ return 0; }else{ return (strlen($one)>strlen($two))?1:-1; }
Definition: array_multisort()
The function sorts multiple arrays, or sorts multi-dimensional arrays according to a certain dimension or multiple dimensions.
bool array_multisort(array array1 [,mixed arg,[,array ....]])
Example:
$data=array( array("id"=>1,"name"=>4), array("id"=>1,"name"=>2), array("id"=>2,"name"=>3) ); foreach($data as $key=>$value){ $ids[$key]=$value["id"]; $names[$key]=$value["name"] } array_multisort($data,$ids,$names); print_r($data);
Output result:
array( array("id"=>1,"name"=>2), array("id"=>1,"name"=>4), array("id"=>2,"name"=>3) );
Recommended: "PHP Video Tutorial"
The above is the detailed content of Summary of common array sorting methods in PHP. For more information, please follow other related articles on the PHP Chinese website!