您不能一次选择所有内容并按列排序吗?
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 />";
}
}
}