Sort an array of objects based on a specific property
P粉426780515
2023-08-21 15:57:31
<p>How can I sort this array of objects by a field such as <code>name</code> or <code>count</code>? </p>
<pre class="brush:php;toolbar:false;">Array
(
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
....</pre>
<p><br /></p>
This is a better way to use closures
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.
Using usort, here is an example adapted from the manual:
You can also use any callable as the second parameter. Here are some examples:
Using Anonymous functions (starting with PHP 5.3)
Used inside the class
Using arrow functions (starting with PHP 7.4)
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
.