P粉2855875902023-08-22 00:56:43
This is a better way to use closures
usort($your_data, function($a, $b) { return strcmp($a->name, $b->name); });
Please note that this is not in the PHP documentation, but if you are using version 5.3, closures are supported and callable parameters can be provided.
P粉0200855992023-08-22 00:31:39
Using usort, here is an example adapted from the manual:
function cmp($a, $b) { return strcmp($a->name, $b->name); } usort($your_data, "cmp");
You can also use any callable as the second parameter. Here are some examples:
Using Anonymous functions (starting with PHP 5.3)
usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
Used inside the class
usort($your_data, array($this, "cmp")); // "cmp"应该是类中的一个方法
Using arrow functions (starting with PHP 7.4)
usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
Also, if you want to compare values, fn($a, $b) => $a->count - $b->count
as a "comparison" function should do the trick , or, if you want to do the same thing another way, starting with PHP 7 you can use the spaceship operator, like this: fn($a, $b) => ; $a->count <=> $b->count
.