Sort an array of objects based on a specific property
P粉426780515
P粉426780515 2023-08-21 15:57:31
0
2
603
<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>
P粉426780515
P粉426780515

reply all(2)
P粉285587590

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粉020085599

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->countas 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) =&gt ; $a->count <=> $b->count.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template