2

我有以下代码来填充表格中的城市。

$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);


echo "<table>";
while ($row = mysql_fetch_assoc($cities_result))
{
    echo "<tr>";
    echo "<td>".$row['city_name'] . "</td>";
    echo "</tr>";
}
echo "</table>";

现在我需要按地区对每个城市进行分组,所以我创建了一个名为的表,并在新表的新列中city_region_selection添加了一个。Foreign key"region_id"city_selection tableregion_id

我现在正在努力使用 PHP 在一个漂亮的 html 表中呈现这些数据。

甚至可以先用 region_name 填充一个表格行,然后再填充一些包含该地区城市的子行?详情请看这张图片:

http://oi48.tinypic.com/2uq0z9x.jpg

4

1 回答 1

2

你只需要做一点预处理:

/* SQL
   SELECT
      city_name,
      region_name
   FROM
      city_selection
      NATURAL JOIN city_region_selection
SQL */

$regions = array();
while ($result->fetch()) {
   if (!isset($regions[$result->region_name])) {
      $regions[$result->region_name] = array();
   }
   $regions[$result->region_name][] = $result->city_name;
}

具有 SQL 焦点的替代方法

/* SQL
   SELECT
      region_name,
      GROUP_CONCAT(city_name SEPARATOR ',') cities
   FROM
      city_selection
      NATURAL JOIN city_region_selection
   GROUP BY
      region_name
*/

$regions = array();
while ($result->fetch()) {
   $regions[$result->region_name] = explode(',', $result->city_name);
}

帮助

请注意,while语法只是被删节了。你可能会用

while ($row = mysql_fetch_assoc($cities_result)) {
   $regions[$row['region_name']] = explode(',', $row['city_name']);
}

... 例如

一旦regions构建,只需执行以下操作:

foreach ($regions as $region => $cities) {
   echo "<tr><td>$region</td></tr>";
   foreach ($cities as $city) {
      echo "<tr><td class="tabbed">$city</td></tr>";
   }
}
于 2012-05-21T15:54:33.843 回答