用PHP从数据库行格式化层次结构


Formatting Hierarchical Structure from Database rows with PHP

我正竭尽全力,试图用PHP从数据库行中格式化分层布局。有人能帮我吗?我试过使用foreach循环,如果国家不同,可以设置开关,但我无法让其他人正确格式化。

ID      City        State         Country
==================================================
1       Dallas      Texas         United States
2       Baltimore   Maryland      United States
3       Houston     Texas         United States
4       Essex       London        United Kingdom
5       Salford     Manchester    United Kingdom

给我以下(最好在多选字段中)

United States
--Maryland
----Baltimore
--Texas
----Dallas
----Houston
United Kingdom
-- London
---- Essex
-- Manchester
----Salford

<select multiple="yes" name="locations">
  <option value="United States">United States</option>
  <option value="Maryland">-- Maryland</option>
  <option value="Baltimore">---- Baltimore</option>
  <option value="Texas">-- Texas</option>
  <option value="Dallas">---- Dallas</option>
  <option value="Houston">---- Houston</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="London">-- London</option>
  <option value="Essex">---- Essex</option>
  <option value="Manchester">-- Manchester</option>
  <option value="Salford">---- Salford</option>
</select>

这里的基本目标是对行进行迭代,将它们放在您要查找的层次结构中。我建议这样做:(这可能会给你带来一些E-STRIT警告,但在这里和那里进行一点错误检查从未导致任何人死亡)。然后,您可以随意从层次结构中进行打印。

$locations = array();
foreach($rows as $row)
    locations[$row->Country][$row->state][$row->city] = $row->id;
echo '<select multiple="yes" name="locations">';
$foreach($locations as $country=>$states){
    echo "<option value='$country'>$country</option>";
    $foreach($states as $state=>$cities){
        echo "<option value='$state'>-- $state</option>";
        $foreach($cities as $city=>$id)
            echo "<option value='$city'>---- $city</option>";
    }
}
echo '</select>';