在名字的第一个字母上组合PHP结果 [英] Group PHP results on first letter of name
本文介绍了在名字的第一个字母上组合PHP结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个查询,该查询获取按last_name排序的所有记录.现在,我想创建一个循环,将这些结果按姓氏的首字母分组,并在该组上方显示该字母,即
I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the letter above the group i.e.
A
-----------
Albert
Alfred
C
-----------
Charles
D
-----------
Delta etc...
谢谢!
推荐答案
在MySQL
侧按lastname
排序结果,并在PHP
侧跟踪第一个字母的变化:
Order the results by lastname
on MySQL
side and track the change of the first letter on PHP
side:
<?php
$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");
while ($rec = mysql_fetch_assoc($rs)) {
if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
$initial = strtoupper(substr($rec['lastname'], 0, 1));
print "$initial\n";
}
print $rec['lastname'] . "\n";
}
?>
这篇关于在名字的第一个字母上组合PHP结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文