Page 1 of 1
Sort object
Posted: Thu Sep 16, 2010 8:42 pm
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!
Re: Sort object
Posted: Thu Sep 16, 2010 9:08 pm
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");
Re: Sort object
Posted: Thu Sep 16, 2010 10:18 pm
by xionhack
Honestly I dont understand. That function I just see it comparing two values to see if its the same
Re: Sort object
Posted: Fri Sep 17, 2010 12:03 am
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
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");