Sort object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Sort object

Post by xionhack »

Hello. I have an object like this:

object->object_id
object->object_name
object->object_number

I have an array with many instances of the object, with different values. I want to sort that array to put first the object that the value of object->object_number is higher, and then descending. Please let me know if its not clear! thank you!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Sort object

Post by John Cartwright »

Define your own sort function using usort()

Code: Select all

function cmp($a, $b)
{
    if ($a->object_number == $b->object_number) {
        return 0;
    }
    return ($a->object_number < $b->object_number) ? -1 : 1;
}

usort($your_array_of_objects, "cmp");

xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Re: Sort object

Post by xionhack »

Honestly I dont understand. That function I just see it comparing two values to see if its the same
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Sort object

Post by requinix »

Yeah. Isn't that basically what sorting comes down to: whether two things are the same or not?
Read the manual page.

Also, as a sidenote:
1. All you have to do is return a number, not necessarily -1/0/1. Only the sign matters (negative means A<B, zero mean A=B, positive means A>B).
2. For principle's sake, I'd put the function inside the class as a static method.
3. I wanted to just make a couple modifications to John's code but I ended up writing it in my own style instead :banghead:

Code: Select all

class Whatever {

    public static $SORT = SORT_ASC;

    // ...

    public static function sort(Whatever $a, Whatever $b) {
        return (self::$SORT == SORT_ASC ? 1 : -1) * ($a->object_number - $b->object_number);
    }

    // ...

}

// ...
Whatever::$SORT = SORT_DESC;
usort($array_of_objects, "Whatever::sort");
Post Reply