0

我有一个包含位置列表的数据库,例如:

C_ID   |   Name 

1      |   Italy
2      |   Germany
3      |   France
4      |   Spain

在一张单独的表格中,列出了来自这些国家的人员名单,

P_ID  |  Name   |  C_ID

1     | John    | 1
2     | Mark    | 1
3     | Paul    | 2
4     | Pierre  | 3
5     | Alan    | 2

我已经在一个带有连接的 SQL 查询中抓取了这些数据......

SELECT locations.name as locaname, people.name as peoplename
FROM locations
INNER JOIN people
ON locations.c_id=people.c_id
ORDER BY locations.name";

这为我提供了:

Italy John
Italy Mark
Germany Paul
Germany Alan
France Pierre

但是,我想要实现的是一个无序列表,由 PHP 响应。用按国名分组的人名。与重复国名相反。我尝试过使用数组,但是我对 PHP/MySQL 的了解让我失望了……

4

1 回答 1

1

尝试:

$sql = <<<END
SELECT locations.name as locaname, people.name as peoplename
FROM locations
INNER JOIN people
ON locations.c_id=people.c_id
ORDER BY locations.name"
END;
$query = mysql_query($query) or die($sql . ' - ' . mysql_error());
$result = array();
while ($row = mysql_fetch_array($query)) {
  $result[$row[0]][] = $row[1];
}
print_r($result);

$row[0]是国家,$row[1]是人的名字。while循环中的函数是这里的关键。这有很多作用。它基本上将一个条目添加到由国家名称键入的结果数组中,并将人名附加到它存储在那里的数组中。

编辑:以列表形式订购:

echo '<ul>';
foreach ($result as $country => $persons) {
  echo "<li>$country\n<ul>\n";
  foreach ($persons as $person) {
    echo "<li>$person</li>\n";
  }
  echo "</ul></li>\n";
}
echo '</ul>';
于 2009-11-28T16:33:49.467 回答