Re: sorting multi-dimensional arrays

From: Date: Sat, 14 Apr 2001 09:49:00 +0000
Subject: Re: sorting multi-dimensional arrays
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-48523@lists.php.net to get a copy of this message
Try this (it should work): while(list($k, $v) = each($myarray)){ $myarray[$k] = (int) $v; } arsort($myarray); reset($myarray); while(list($k, $v) = each($myarray)){ echo $k, ' == ', $v, "<BR>\n; } For better comprehension look at this post: >Hey guys.. > >I have this array that looks like this: > >$myarray = ( "apples" => 0, "oranges" => 2, "peaches" => >9, "pineapples" => >12, "stovetopstuffing" => 3, "grits" => 8); > >Fine and dandy. But, when I try to sort it in reverse order: > >arsort($myarray); > >I get THIS for output, obviously NOT what I want: > >peaches => 9 >grits => 8 >stovetopstuffing => 3 >oranges => 2 >pineapples => 12 >apples => 0 > >Obviously, I want the pineapples entry to be at the top, since it has the >highest value. What do I need to do? You have stored strings as your values, instead of ints. IE: (string) '9' > (string) '12' returns TRUE You will need to take care in creating your array to have (int) values instead of strings. If all else fails, the following should work: while(list($k, $v) = each($myarray)){ $myarray[$k] = (int) $v; } arsort($myarray); reset($myarray); while(list($k, $v) = each($myarray)){ echo $k, ' == ', $v, "<BR>\n; } ----- Original Message ----- From: <Shane43@aol.com> To: <php-general@lists.php.net> Sent: Saturday, April 14, 2001 5:19 AM Subject: [PHP] sorting multi-dimensional arrays > I have a question about sorting multidimensional arrays. Here is my problem: > > I have an 2-d array: > $joke[1][rating]=10; > $joke[2][rating]=20; > $joke[3][rating]=15; > .... > > I would like to sort the jokes into an array based on the rating from highest > to lowest. The end result would be something like this: > Joke 2 : 20 points > Joke 3: 15 points > Joke 1: 10 points > > How do I accomplish this? > > I have tried fooling around with sort(), arsort(), and array_multisort(), but > I just can't get it. Thank you very much for your time. > > Shane >

« previous php.general (#48523) next »