Re: Grouping
| From: | Richard Lynch | Date: | Thu, 19 Jan 2006 19:57:59 +0000 |
| Subject: | Re: Grouping | ||
| References: | 1 2 3 4 5 6 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-228853@lists.php.net to get a copy of this message | ||
On Thu, January 19, 2006 12:19 pm, Jeffrey Pearson wrote:
> OK. I know I did this a LONG time ago but I don't remember how I did
> it. Thus, my post.
>
> I have a list of last names from a MySQL database. I need to display
> them grouped by the first letter of their last names and insert a
> separator on display. Similar to a phone book. So it looks like;
It might be slightly more clear to have MySQL get the initial letter,
rather than PHP...
//Also note use of 'upper' in case you have mixed case names.
// You presumably want all caps for alpha section names
$query = "select upper(substring(name, 0, 1)), name from names order
by name";
//next line is bad code, for simplicity of example:
$names = mysql_query($query) or die(mysql_error());
$last_letter = 'an extremely unlikely single character';
while (list($letter, $name) = mysql_fetch_row($names)){
if ($letter != $last_letter) echo $letter, "<hr />\n";
echo $name, "<br />\n";
}
As an exercise for the reader, you should consider lumping all non A-Z
characters together, rather than individually.
--
Like Music?
http://l-i-e.com/artists.htm