您是否希望列表完全按字母顺序排列?或者只是按照第一个字母分组?你是否在意没有开始任何单词的信件不会显示为标题?例如,如果您没有任何以'x'开头的单词,您是否还需要看到一个没有任何内容的'X'类别,还是应该从'W'跳到'Y'?
确切的实施可能会根据这些问题的答案而有所不同。这是一个解决方案,应该按照字母顺序完全显示列表,跳过没有任何单词的类别。 (不知道你想要什么样的标记,这是相当的骨头)。
$result = mysql_query("SELECT col FROM table ORDER BY col");
$lastFoundLetter = '';
while($row = mysql_fetch_array($result)) {
//get the first letter of the current record
$firstLetter = substr($row['col'], 0, 1);
if ($firstLetter != $lastFoundLetter) {
//you've started a new letter category
if ($lastFoundLetter != '') {
//if there's a real value in $lastFoundLetter, we need to close the previous div
echo "</div>";
}
echo "<div id='" . strtoupper($firstLetter) . "'>";
echo strtoupper($firstLetter) . "<br/>";
$lastFoundLetter = $firstLetter;
}
echo $row['col']. "<br/>";
}
//close the last div
if ($lastFoundLetter != '') {
echo "</div>";
}
谢谢Jay!你的建议帮助了我。我用一个for来检查数组,并检查该项目的第一个字母是否与前一个项目的第一个字母不同。 – Cosmi 2012-03-19 22:21:58