Re: Sorting a Two-Dimensional Array

From: Date: Sat, 15 Jul 2000 00:04:05 +0000
Subject: Re: Sorting a Two-Dimensional Array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-6713@lists.php.net to get a copy of this message
""Waldo L. Jaquith"" <waldo@munkandphyber.com> wrote in message news:B5950AB7.A046%waldo@munkandphyber.com... > Folks, <snip> > I've got an array like this: > > $array[1][id] > $array[1][rating] > $array[2][id] > $array[2][rating] > $array[3][id] > $array[3][rating] > You'll note that it's now in order of 1, 3, 5, instead of 5, 1, 3. In SQL, > this would be wicked easy. I could just do "ORDER BY rating". With > two-dimensional arrays, of course, it's not so easy. I'm aware that I > should be using usort, but I don't know how to go about applying it. I was > hoping for something like "usort($array,rating,asc)", but Momma always > called me a dreamer. :) In SQL, you would probably store ID and RATING in two separate tables and JOIN them, or store them as fields in the same table. What you have here is not really an analogous setup. Why isn't the ID the index? Sorting on RATING would then be easier. If the IDs aren't sequential, use an associative array. Sorting would then be done using asort(). Also, to better mimic the SQL you know and love, you might use a construct like this instead of multidimensional arrays ... $array[index] = "string,string,string,string"; You can explode $array[index] into an array when you need it. Possibly CPU and time expensive, but probably easier to bend your mind around than multi-dimensional arrays. You can use a string as "index", and sort using the index (with ksort() )or the beginning of each element (with asort() ). -- O.

« previous php.general (#6713) next »