PHP - 从数据库建立多层次的关联数组(由DB状态排序市) [英] PHP - build multilevel associative array from database (sorting cities by state from db)
问题描述
我有点新的PHP,并已剑拔弩张我的大脑在过去的几个小时,试图弄清楚这一点。我需要通过国家的城市从数据库进行排序。我用下面的查询检索数据集:
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
这显示了我,当我运行它在phpMyAdmin查询需要的信息,但我似乎无法弄清楚如何得到它到一个数组和循环吧。
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.
我要输出的格式为:
CA
Los Angeles
San Francisco
New York
Brooklyn
Buffalo
我还需要能够使每一个城市返回一个链接,但我pretty相信我能做到这一点与.item ['$城市'。
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']."
任何帮助是极大AP preciated!
Any help is greatly appreciated!
推荐答案
谢谢你们!
结束了使用以下code:
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>";
}
这篇关于PHP - 从数据库建立多层次的关联数组(由DB状态排序市)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!