按字母顺序列出数组值并带有字母标题
我需要一些帮助来解决这个问题。我正在尝试创建一个函数,该函数按字母顺序输出数组中的值,但在到达当前字母的末尾后也会回显新的字母标题。例如:
A
亚马逊
美国
B
巴哈马
百慕大
C
加拿大
柬埔寨
等。
到目前为止,我可以通过重复“$result”中的代码来做到这一点,但我知道这不是一个好的做法,所以我正在寻找包含变量的东西而不是“a%”,并在每次成功运行脚本后自动递增该字母(在 Z 处停止)。
<?php
$username = "myusername";
$password = "mypsswrd";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mydb",$dbhandle)
or die("Could not select database");
$result = mysql_query("SELECT user, name FROM users WHERE name like 'a%' ORDER BY name");
echo "A<br />";
while ($row = mysql_fetch_array($result)) {
echo "<a href=\"/artists/artist.php?user=".$row{'user'}."\">".$row{'name'}."</a><br />";
}
echo "<br />";
I need some help figuring this out. I am trying to create a function that outputs values in an array alphabetically, but also echoes a new letter title after it reaches the end of the current letter. Ex:
A
Amazon
America
B
Bahamas
Bermuda
C
Canada
Cambodia
Etc.
I can do it by repeating the code from "$result" on so far, but I understand it's just not good practice, so I'm looking for something that includes a variable instead of the "a%", and autoincrements the letter (stopping at Z), after each successful run of the script.
<?php
$username = "myusername";
$password = "mypsswrd";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mydb",$dbhandle)
or die("Could not select database");
$result = mysql_query("SELECT user, name FROM users WHERE name like 'a%' ORDER BY name");
echo "A<br />";
while ($row = mysql_fetch_array($result)) {
echo "<a href=\"/artists/artist.php?user=".$row{'user'}."\">".$row{'name'}."</a><br />";
}
echo "<br />";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)