Home  >  Article  >  Backend Development  >  PHP array sort usort uksort sort function

PHP array sort usort uksort sort function

高洛峰
高洛峰Original
2016-11-29 14:48:281933browse

Sort the array: The usort() function uses a user-defined function to sort the array. The example code is as follows:

function cmp($a, $b) //User-defined callback function

{

if($a ==$b) //If the two parameters are equal

{

return 0; //Return 0

}

return($a>$b)?-1:1; //If the first parameter If it is greater than the second one, 1 will be returned, otherwise -1

}

$a=array(3,2,5,6,1); Use a custom function to sort the array

foreach($a as $key=>$value) //Loop to output the sorted key-value pairs

{

echo "$key:$valuen";

}

Note: If the comparison results of two elements are the same, their order in the sorted array is undefined. Before PHP 4.0.6, the user-defined function will retain the original order of these elements, but since 4.1. A new sorting algorithm was introduced in 0, and the result will not be like this, because there is no effective solution for this.

Sort the array key name uksort(array, sorttype), the example code is as follows:

function cmp($a , $b) //User-defined callback function

{

if($a==$b) //If the two parameters are equal

{

return 0; //Return 0

}

return ($a>$b)?-1:1; //If the first parameter is greater than the second parameter, return 1, otherwise -1

}

$a=array(4=>"four",3 = >"three",20 =>"twenty",10=>"ten"); //Define an array

uksort ($a,"cmp"); //Use a custom function to sort the array key name Sorting

foreach($a as $key=>$value) //Loop to output the sorted key-value pairs

{//

echo "$key:$valuen";

}

uksort() The function uses a user-defined comparison function to sort the array by key name and maintains the index relationship. If successful, it returns true, otherwise it returns false.

If the array to be sorted needs to be sorted by an unusual criterion, then it should To use this function, the custom function should accept two parameters, which will be filled with a pair of key names in the array. The comparison function must return a value less than zero when the first parameter is less than, equal to, or greater than the second parameter. , equal to zero, or an integer greater than zero. The

sort() function sorts the values ​​of the given array in ascending order.

Note: This function assigns a new key name to the unit in the array, and the original key name will be deleted. If successful, it returns true, otherwise it returns false. The example code is as follows:

$fruits=array("lemon","orange","banana","apple"); //Define an array

sort($fruits) ; ; Key value pair

}//

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn