Sort an array: the Usort () function uses a user-defined function to sort the array, with the instance code as follows:
function cmp ($a, $b)//user-defined callback function
{
if ($a = = $b)//If two parameters are equal
{
return 0; Returns 0
}
return ($a > $b) -1:1; If the 1th parameter is greater than 2nd, return 1, otherwise-1
}
$a =array (3,2,5,6,1); Define an array
Usort ($a, "CMP"); Use a custom function to sort an array
foreach ($a as $key + $value)//Cyclic output sorted key-value pair
{
echo "$key: $valuen";
}
Note: If two elements compare the same result, their order in the sorted array is undefined, and before PHP 4.0.6, the user-defined function retains the original order of the elements, but because of the new sorting algorithm introduced in 4.1.0, the result is not, Because there is no effective solution to this.
Sort the array key names Uksort (Array,sorttype) with the following instance code:
function cmp ($a, $b)//user-defined callback function
{
if ($a = = $b)//If two parameters are equal
{
return 0; Returns 0
}
return ($a > $b) -1:1; If the 1th parameter is greater than 2nd, return 1, otherwise-1
}
$a =array (4=> "Four", 3 = "three", "Twenty",10=> "ten"); Define an array
Uksort ($a, "CMP"); Sorting the array key names using a custom function
foreach ($a as $key + $value)//Cyclic output sorted key-value pair
{//
echo "$key: $valuen";
}
The Uksort () function uses a user-defined comparison function to sort the array by the key name, maintains the index relationship, and returns true if successful, otherwise false.
If the array to be sorted needs to be sorted with an unusual standard, then this function should be used, and the custom function should accept two parameters, which will be populated by a pair of key names in the array, the comparison function must return one less than 0, equal to zero, when the first argument is less than, or greater than, the second argument. Or an integer greater than 0.
The sort () function sorts the values of the given array in ascending order.
Note: This function assigns the new key name to the cells in the array, the original key names are deleted, returns true if successful, otherwise false, the instance code is as follows:
$fruits =array ("Lemon", "orange", "banana", "apple"); Define an array
Sort ($fruits); Sorting an array
foreach ($fruits as $key + $val)////Loop output array after sorting the key-value pairs
{
echo "$key = $valn"; Output key-value pairs
}//