phparrayssortingobjectmultidimensional-array

Sort array of objects by one property


How can I sort this array of objects by one of its fields, like name or count?

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
        )

   ....

Solution

  • Use usort to customize the comparison function. Here's 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 argument. Here are some examples:

    Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.