Array of sorting PHP stdClass objects by ID

I have a pretty big array that looks like

Array(
   [0] => stdClass Object
        (
            [id] => 8585320
            [title] => the title
            [type] => page
            [url] => link.com
            [excerpt] => brief description
        )

    [1] => stdClass Object
        (
            [id] => 8585320
            [title] => the title
            [type] => page
            [url] => link.com
            [excerpt] => brief description
        )
 )

I have no explicit control over how the array is formed, and how this happens, it seems that there is little logic in it. But I was stuck with him. Therefore, I need to make the array sort it by the numerical object of each stdClass object, and then make sure that the identifier is from the largest to the smallest and from the smallest to the largest. Keeping the current structure of the combination of array objects all the time

I can’t even think now how I will need to sort it the way I need. Since it has been a long time.

UPDATE

public function updateRet($a, $b) {
        return $b->id - $a->id;
    }
usort($ret, 'updateRet');  
+5
source share
1 answer

usort:

function compare_some_objects($a, $b) { // Make sure to give this a more meaningful name!
    return $b->id - $a->id;
}

// ...

usort($array, 'compare_some_objects');

PHP 5.3 , :

usort($array, function($a, $b) { return $b->id - $a->id; });
+10

All Articles