[英]order by alphabet PHP, MySql but list the letter before each group
Say I had a table with:假设我有一张桌子:
First | Last
-------------------
Bob Dylan
Ashley Scott
Lol Cats
black cake
It would order them but do它会订购它们,但做
A:
Ashley Scott
B:
Bob Dylan
Black Cake
L:
lol cats
I know how to list by abc from MySql.我知道如何从 MySql 按 abc 列出。 but i want to have it put the letter before each group of names.但我想让它把字母放在每组名字之前。 So i can make a nice looking interface, and at the top of the page have AB C D letters at the top that went contacts#letterL所以我可以制作一个漂亮的界面,在页面顶部有 AB C D 字母在顶部是contacts#letterL
I know how to do the #links in a url.我知道如何在 url 中执行 #links。 Its just the div Id.它只是 div Id。 I know how to grab from MySql.我知道如何从 MySql 中获取。 The part i'm not sure on is echoing the letter before the group of names that start with that letter.我不确定的部分是在以该字母开头的名称组之前呼应该字母。
I was thinking of getting the first letter of the name of saving it in a variable.我正在考虑将名称的第一个字母保存在变量中。
if ($lastletter == $currentleter) {
echo name
} else {
$lastletter = $currentleter;
echo '<div id="Letter ' . $currentleter . '" class="letterheader">' . $currentleter . '</div>';
}
Not sure if this idea would be a efficient idea.不确定这个想法是否有效。 Would this be the right away of doing this?这样做是正确的吗?
Untested code but something like this should work:未经测试的代码,但这样的东西应该可以工作:
$currentleter = substr($name , 0 , 1);
if ($lastletter != $currentleter){
echo '<div id="Letter' . $currentleter . '" class="letterheader">' . $currentleter . '</div>';
$lastletter = $currentleter;
}
echo $name;
You can select the records with order by first name.您可以 select 按名字排序的记录。
$sql = "select * from tblname order by firstname";
$lastletter = "A";
echo $lastLetter;
if ($lastLetter != substr($firstname, 0,1))
echo $lastLetter;
echo $firstname;
This looks like a pretty good solution except IDs must not have spaces in them so you wanna change这看起来是一个很好的解决方案,除了 ID 中不能有空格,所以你想改变
<div id="Letter '. $currentleter. '" class="letterheader">
to <div id="Letter '. $currentleter. '" class="letterheader">
到
<div id="Letter_'. $currentleter. '" class="letterheader">
. <div id="Letter_'. $currentleter. '" class="letterheader">
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.