Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - build multilevel associative array from database (sorting cities by state from db)

I'm somewhat new to php and have been rattling my brain for the past few hours trying to figure this out. I need to sort cities by state from a database. I used the following query to retrieve the data set:

SELECT state, city FROM table ORDER BY state ASC, city ASC  

This shows me the information I need when I run it as a query in phpMyAdmin, however I can't seem to figure out how to get it into an array and loop it.

The format I need to output is

CA
   Los Angeles
   San Francisco
New York
   Brooklyn
   Buffalo

I also need to be able to make each city return a link, but I'm pretty sure I can do that with ".item['$city']."

Any help is greatly appreciated!

like image 783
Mike Avatar asked May 01 '26 17:05

Mike


1 Answers

Thanks Guys!

Ended up using the following code:

$query = ('SELECT DISTINCT state,city FROM table ORDER BY state ASC, city ASC');
$result = mysql_query($query);
$states = array();
while ($row = mysql_fetch_assoc($result)) {

    if (!isset($exists[$row['state']])) {

        echo "<div id='location'><div class='state'><p>" . $row['state'] . "</p>";

        $exists[$row['state']] = true;
    }
    echo "<div class='city'><p><a href='?city=".$row['city']."' target='_blank'>".$row['city']."</a></p></div>";
}   
like image 199
Mike Avatar answered May 03 '26 07:05

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!