Php shares array sorting code
This article mainly introduces the php code for sorting arrays. For more information, see
The Code is as follows:
<? Php
Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // www.jb51.net 'scrolling = 'no'>
Sort Arrays
The usort () function uses a user-defined function to sort arrays.
*/
Function cmp ($ a, $ B) // user-defined callback function
{
If ($ a ==$ B) // if the two parameters are equal
{
Return 0; // return 0
}
Return ($ a> $ B )? -; // If the number of 1st parameters is greater than 2nd, 1 is returned. Otherwise,-1 is returned.
}
$ A = array (3, 2, 5, 6, 1); // defines an array
Usort ($ a, "cmp"); // use a UDF to sort arrays.
Foreach ($ a as $ key => $ value) // cyclically outputs sorted key-value pairs
{
Echo "$ key: $ valuen ";
}
/*
Note: If the comparison results of the two elements are the same, their order in the sorted array is not defined. Before php 4.0.6, user-defined functions retain the original sequence of these elements. However, because a new sorting algorithm is introduced in 4.1.0, this is not the case because there is no effective solution.
*/
// Sort the array key names by uksort (array, sorttype)
Function cmp ($ a, $ B) // user-defined callback function
{
If ($ a ==$ B) // if the two parameters are equal
{
Return 0; // return 0
}
Return ($ a> $ B )? -; // If the number of 1st parameters is greater than 2nd, 1 is returned. Otherwise,-1 is returned.
}
$ 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 names
Foreach ($ a as $ key => $ value) // cyclically outputs sorted key-value pairs
{// Www.jbxue.com
Echo "$ key: $ valuen ";
}/*
The uksort () function uses the custom comparison function to sort the array by key name and maintain the index relationship.
If the call succeeds, true is returned. Otherwise, false is returned.
If the array to be sorted needs to be sorted by an unusual standard, use this function.
The custom function should accept two parameters, which will be filled by a pair of key names in the array. When the first parameter is less than, equal to, or greater than the second parameter, the comparison function must return an integer less than zero, equal to zero, or greater than zero.
*/
/*
The sort () function sorts the values of a given array in ascending order.
Note: This function assigns a new key name to the cell in the array. The original key name is deleted.
If the call succeeds, true is returned. Otherwise, false is returned.
*/
$ Fruits = array ("lemon", "orange", "banana", "apple"); // defines an array
Sort ($ fruits); // sorts the Array
Foreach ($ fruits as $ key => $ val) // cyclically output the sorted key-value pair of the array
{
Echo "$ key = $ valn"; // output key-value pairs
}