Home  >  Q&A  >  body text

Sort an array of objects based on a specific property

<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粉426780515P粉426780515397 days ago527

reply all(2)I'll reply

  • P粉285587590

    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.

    reply
    0
  • P粉020085599

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

    reply
    0
  • Cancelreply