我正在尝试使用来自mysql表的已分配链接对名称列表进行排序 希望它在html中看起来像这样:
<h3>A</h3>
<ul>
<li>Andrea</li>
<li>Arron</li>
</ul>
到目前为止,我能够按字母顺序列出字母和名称,但我不知道如何制作一个循环,列出标题为'A'等标题下以'A'开头的所有名称。
<?php
$connection = mysqli_connect('localhost', 'root', '', 'database');
$query = "SELECT * FROM users ORDER BY name";
$result = $connection->query($query);
$azRange = range('A', 'Z');
foreach ($azRange as $letter){
echo "<h3>" . $letter . "</h3>";
}
echo "<ul>";
while($row = $result->fetch_array()){
echo "<li><a href=\"" . $row['link'] . "\">" . $row['name'] . "</a></li>";
}
echo "</ul>";
?>
谢谢。
答案 0 :(得分:2)
试试这个:
<?php
$connection = mysqli_connect('localhost', 'root', '', 'database');
$query = "SELECT * FROM users ORDER BY name";
$result = $connection->query($query);
$names = $result->fetch_all(MYSQLI_ASSOC);
$idx = 0;
$namesCount = count($names);
$azRange = range('A', 'Z');
foreach ($azRange as $letter) {
echo "<h3>" . $letter . "</h3>";
echo "<ul>";
for (; $idx < $namesCount; ++$idx) {
$row = $names[$idx];
if (strtoupper($row['name'][0]) === $letter) {
echo "<li><a href=\"" . $row['link'] . "\">" . $row['name'] . "</a></li>";
} else {
break;
}
}
echo "</ul>";
}
答案 1 :(得分:1)
您需要检查每个$row['name']
的第一个字母并控制此字母的更改。因此,如果第一个字母为'A'
几行,然后它已更改为'B'
- 这意味着您需要回显此新字母(B
)。
echo "<ul>";
// init first letter with an empty value
$first_letter = "";
while($row = $result->fetch_array()){
// get first letter of current name
$first_letter_of_name = substr($row['name'], 0, 1);
if ($first_letter_of_name != $first_letter) {
// first letters differ, this
// means that new letter is here
// Echo this new letter
echo '<li>Letter: <b>' . $first_letter . '</b></li>'
// Change flag's value
$first_letter = $first_letter_of_name;
}
echo "<li><a href=\"" . $row['link'] . "\">" . $row['name'] . "</a></li>";
}
echo "</ul>";
答案 2 :(得分:0)
我会先拆分数据:
$query = "SELECT * FROM users ORDER BY name";
$result = $connection->query($query);
$data = array();
while($row = $result->fetch_array()){
$firstLetter = strtoupper($row['name'][0]);
$data[$firstLetter][] = $row;
}
foreach ($data as $letter => $letterData){
echo "<h3>" . $letter . "</h3>";
echo "<ul>";
foreach ($letterData as $row) {
echo '<li><a href="' . $row['link'] . '">' . $row['name'] . '</a></li>';
}
echo "</ul>";
}
有两个原因,为什么我这样做:
if()
)。因此代码不那么复杂。注意:为了安全使用多字节字符串,您应该使用类似
的内容$firstLetter = mb_strtoupper(mb_substr($row['name'], 0, 1,'UTF8'));
PDO会更短(避免第一个循环):
$query = "SELECT UPPER(LEFT(name,1)) as first_letter, u.* FROM users u ORDER BY name";
$data = $connection->query($query)->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
答案 3 :(得分:-1)
使用开关语句;这样当从数据库传递的字母与A匹配时,运行一定的代码;注意从数据库中获取的数据中收集第一个字符(您可以使用此php函数strchr(string, charToFind);
)并使用switch语句进行比较;
$variable
switch($variable){
case 'A':
#output here
break
case 'a':
#output here
break
}