Re: Sorting a Two-Dimensional Array
| From: | Waldo L. Jaquith | Date: | Sun, 16 Jul 2000 22:33:42 +0000 |
| Subject: | Re: Sorting a Two-Dimensional Array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-6853@lists.php.net to get a copy of this message | ||
"Waldo L. Jaquith" <waldo@munkandphyber.com> wrote:.
> 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. :)
"O." <datahntr@yahoo.com> wrote:
> 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() ).
Unfortunately, the setup, as you see it, is how it has to be. Given the
need for speed and the dynamic nature of these IDs and ratings (changing
frequently as a result of just-occurred user input), it's not practical to
spend time writing the data to a table and then extracting it again, only to
delete it.
I will, however, try storing the strings as CSV and exploding them -- it's
just so crazy, it just might work. :) I'll also try Christopher Thompson's
<ct@arborinternet.com> fine sorting algorithm that he whipped up for me.
Thanks, folks.
Best,
Waldo
Waldo L. Jaquith
< waldo@munkandphyber.com >
< 804/979.2980 >
// Munk & Phyber
// 110B Second Street NE
// Charlottesville, VA 22902