7

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');  
0

1 Answer 1

15

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; });
Sign up to request clarification or add additional context in comments.

11 Comments

Im getting an invalid comparison function, Im thinking its cause I have an array with the objects inside of it. so I have to get it to do $b[x]->id somehow but like that its not working
@chris: Use the first method then. Make sure the function is defined properly.
thats the problem, not sure how to define it properly I gave it a different name for the function, but essentially left the rest alone, and am using it just as above. But not getting lucky. Could it be also because Im running this in an OOP style coding? can I pass it like $this->compare_some_objects (again changed that name but just for reference here)
@chris: It works correctly for me. Can you post your code?
@chris: Anyway, the problem is that it's a public function, which means you put it inside a class. It should not be inside a class. If you want it to be inside a class, make it a public static function and change 'updateRet' to array('YourClassName', 'updateRet').
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.