RE: [PHP] Sorting a Two-Dimensional Array

From: Date: Sat, 15 Jul 2000 02:26:26 +0000
Subject: RE: [PHP] Sorting a Two-Dimensional Array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-6725@lists.php.net to get a copy of this message
Manually sorting an multi dimensional array is no different a single dimensional array. There are many sorting algorithms. Here is a simple though not particularly fast one. This code was quickly typed in and has not been tested. $key = 'rating'; $n = count($array); for($i=0; $i<$n-1; ++$i){ for($j=$i+1; $j<$n; ++$j){ if($array[$i][$key] > $array[$j][$key]){ $tmp = $array[$i]; $array[$i] = $array[$j]; $array[$j] = $tmp; } } } > -----Original Message----- > From: Waldo L. Jaquith [mailto:waldo@munkandphyber.com] > Sent: Friday, July 14, 2000 3:22 PM > To: php-general@lists.php.net > Subject: [PHP] Sorting a Two-Dimensional Array > > > Folks, > > I've searched the archives over for this, but I can't find a > response that's > really pertinent to what I'm doing. I'm new at multi-dimensional > arrays, so > please bear with me. :) > > 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] > > I'd like to sort by rating. So if the data looked like this: > > $array[1][501] > $array[1][5] > $array[2][467] > $array[2][1] > $array[3][468] > $array[3][3] > > I'd like to sort by rating, for it to end up looking like this: > > $array[2][467] > $array[2][1] > $array[3][468] > $array[3][3] > $array[1][501] > $array[1][5] > > 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. :) > > Thanks in advance for any help you can offer, fellow PHPers. > > Best, > Waldo > > Waldo L. Jaquith > < waldo@munkandphyber.com > > < 804/979.2980 > > // Munk & Phyber > // 110B Second Street NE > // Charlottesville, VA 22902 > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net > For additional commands, e-mail: php-general-help@lists.php.net > To contact the list administrators, e-mail: php-list-admin@lists.php.net > >

« previous php.general (#6725) next »