Re: Sorting array of objects

From: Date: Mon, 05 Apr 2004 05:03:40 +0000
Subject: Re: Sorting array of objects
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-182325@lists.php.net to get a copy of this message
Hi, Monday, April 5, 2004, 1:03:17 PM, you wrote: RH> Hi there, RH> Supposed I have an array of objects, like: $this[$i]->>property1 $this[$i]->>property2 RH> is there any 'cheap' way to sort the array according to the values of RH> property1? RH> The only way I thought I would be able to accomplish this is to RH> transform this into an assoc array or something like it and then sort RH> it ... RH> I found plenty of functions for dealing with plain arrays, but nothing RH> - easy to use - for this. Am I just blind or do I finally have to write RH> a function doing that on my own? RH> And if so - anyone who had to do this before and come up with a really RH> fast solution (I guess my attempts would work - but not very efficient) RH> Thanks RH> Richard This should do what you want, though I think your example is confusing... <?php function cmp_ascending($k1, $k2) { global $a; if ($a[$k1]->property == $a[$k2]->property) { return 0; } return ($a[$k1]->property < $a[$k2]->property) ? -1 : 1; } class test{ var $property = 0; function test($val){ $this->property = $val; } } $a[] = new test(7); $a[] = new test(1); $a[] = new test(5); $a[] = new test(3); print_r($a); uksort($a, "cmp_ascending"); while (list($key, $value) = each($a)) { echo "$key: $value->property <br>"; } -- regards, Tom

« previous php.general (#182325) next »