uksort
bool uksort(array array, string func)
|
array
|
Array to sort using the supplied function
|
|
func
|
Function with which to sort the array keys
|
Sorts the elements of an array by keys, using a user-defined function.
Returns:
TRUE on success; FALSE on failure
Description:
uksort() sorts array
based on the keys, preserving the key/value relationships. The keys are sorted using a bubblesort algorithm, which uses the user-defined comparison function named by func
to evaluate whether the two elements being compared are equivalent, the first is greater than the second, or the second is greater than the first. This function can be used to modify the order in which keys are sorted, rather than using the standard order supplied with ksort(). For example, you can sort the keys in reverse order.
func
should be written to accept two parameters, which it compares. If they're considered equivalent, 0 should be returned. If the first is considered to be greater, 1 should be returned. If the second is considered to be greater, -1 should be returned.
Version:
PHP 3 since 3.0.4, PHP 4
See also:
array_multisort()
arsort()
asort()
krsort()
ksort()
natsort()
natcasesort()
rsort()
sort()
uasort()
usort()
Example:
Sort an array by keys using a user-defined comparison function
function uksort_cmp($a, $b) { // Sort items in descending order
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$arr = array("tom" => "Apple", "janet" => "apple",
"fred" => "Banana", "barney" => "banana",
"bullwinkle" => "Carrot", "rocky" => "carrot");
uksort($arr, "uksort_cmp");
while(list($k, $v) = each($arr)) {
echo "$k => $v\n";
}
Output:
tom => Apple
rocky => carrot
janet => apple
fred => Banana
bullwinkle => Carrot
barney => banana
|