你不能一次選擇所有的東西,並按列排序嗎?
SELECT * FROM your_table ORDER BY column_name ASC
然後你就可以通過,如果有行和比較的第一個字母來決定你是什麼字母循環:
$stmt->execute();
if ($stmt->rowCount()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$value = $row['column_name'];
$first_letter = $value[0];
}
}
一旦你的第一個字母,你可以做任何你想要的值
要在這個答案擴展,你可以使用這樣的呼應了同一個標題中的值:
// initialize this variable
$current_letter = '';
// if you get results
if ($stmt->rowCount()) {
// loop through each row
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// when you loop, get the value
$value = $row['column_name'];
// if the value does not have the current letter you are on:
if ($current_letter != $value[0]) {
// echo a header for the new letter
echo "<h2>" . $value[0] . "</h2>";
// set the new letter to the current letter
$current_letter = $value[0];
// echo the actual value
echo $value . "<br />";
} else {
// the value falls under our current letter, echo it
echo $value . "<br />";
}
}
}
非常好的答案,很好的評論,從中學習!我很感激 – Johnny000