PHP - usort
Trieda
Metóda - usort
(PHP 4, PHP 5, PHP 7)
The function is used to sort an array by values using a comparison function defined by the user.
Note: Any existing keys will be removed and new keys will be assigned.
Procedurálne
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| &$array | array | The array we want to sort. | |
| $value_compare_func | callable | Specifies a callable comparison function. The function must return a negative integer if the first argument of the function is less than the second argument, a positive integer if it's greater or zero if they're equal. |
Mávratovej hodnoty
Vracia: bool
Returns true on success, returns false otherwise
.
Príklady
In the first example we sort names according to their lengths:
<?php
$names = array("Elizabeth", "Lisa", "Karen", "Jennifer", "Dorothy", "Sandra");
// The function compares the length of the names:
function compare_name_length($name1, $name2) {
if(strlen($name1) == strlen($name2)) {
return 0;
} else {
return (strlen($name1) < strlen($name2)) ? -1 : 1;
}
}
// Sorting the array according to our comparison function:
usort($names, "compare_name_length");
foreach ($names as $name) {
echo $name . "<br>";
}
In the second example we sort users (an associative array) according to their last name.
<?php
// An associative array we want to sort:
$users = array(
array("firstName" => "John", "lastName" => "Rambo", "age" => 30),
array("firstName" => "Chuck", "lastName" => "Norris", "age" => 40),
array("firstName" => "John", "lastName" => "McClane", "age" => 35),
array("firstName" => "Rocky", "lastName" => "Balboa", "age" => 25),
array("firstName" => "James", "lastName" => "Bond", "age" => 35),
);
// Our function using the built-in strnatcmp() comparison function
function compare_lastName($user1, $user2) {
return strnatcmp($user1["lastName"], $user2["lastName"]);
}
// Sorting the array according to our comparison function:
usort($users, "compare_lastName");
foreach ($users as $user) {
print_r($user);
echo "<br>";
}
