Basic PHP MySQL array grouping question

DanielR

New Member
Quick question, which I think has a very easy solution for someone who has anything above the most rudimentary knowledge of PHP/MySQL as I do.I have a list of cities in a variety of states stored in a database with city, state and some other variables. Right now they get pulled as a list sorted by city name:
  • Anchorage, AK
  • Baltimore, MD
  • Chicago, ILetc etc.
I want to be able to group by state first, then list all the cities that have that state value. So it'd look like:AK
  • Anchorage
  • Juneau
CA
  • Los Angeles
  • San Diego
  • San Francisco
  • etc etc
I know I need to do some sort of foreach and have searched online, but haven't found an example that I can get to work.Here's what I have to pull the basic list:\[code\] $list = mysql_query("SELECT id, alphaname, state FROM regional ORDER BY alphaname",$db);while ($thearray = mysql_fetch_array($list)) { echo "<li><a href='http://stackoverflow.com/questions/2003281/info.html?id=$thearray[id]'>$thearray[alphaname], $thearray[state]</a></li>"; } \[/code\]The only real way I know how to do it would be to run a query for each state which would be a pain and totally stupid... Thanks for any help!Update - solved. I went with rockacola's approach though i-g's worked as well.
 
Back
Top