Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort array of stdClass Objects by id [duplicate]

I've a rather large 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 apparent control over the way the array is formed, and how it comes out, it seems as there is little if any logic to it. But I am stuck with it. So what I need to do is basically take the array sort it numerically by each stdClass Object and then make sure the id's are from largest to smallest and not smallest to largest. All the while maintaining the current structure of the array object combination

I can't even begin to think right now how I would need to approach sorting it the way I need it. As its already been a long enough day.

UPDATE

public function updateRet($a, $b) {
        return $b->id - $a->id;
    }
usort($ret, 'updateRet');  
like image 916
chris Avatar asked Jun 20 '12 23:06

chris


1 Answers

Just use 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');

If you have PHP 5.3 or higher, you can also use an anonymous function:

usort($array, function($a, $b) { return $b->id - $a->id; });
like image 132
Ry- Avatar answered Nov 05 '22 18:11

Ry-