RE: [PHP] categorise list
| From: | John W. Holmes | Date: | Mon, 09 Jun 2003 11:49:11 +0000 |
| Subject: | RE: [PHP] categorise list | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-150750@lists.php.net to get a copy of this message | ||
> I am dispalying data from mysql database using the codes below:
>
> $while($row=mysql_fetch_array($result))
> {
> echo $row[name];
> }
>
> How can i format the above data in this format as shown below? in
> alphabetical order
>
> A
>
------------------------------------------------------------------------
--
> -----------------------------click to go up
> Apple
> Armchair
>
> B
>
------------------------------------------------------------------------
--
> -----------------------------click to go up
> Basket
> Baseball
You need an "ORDER BY name" in your query to get the results sorted
alphabetically, first.
Then, as you loop through the results, you need to "remember" the
current letter you're on. If the letter changes, then output the header
and line showing the next letter.
Something like this:
$old_letter = '';
$query = "SELECT name FROM table ORDER BY name";
$rs = mysql_query($query);
while($row = mysql_fetch_assoc($rs))
{
$current_letter = strtoupper(substr($row['name'],0,1));
if($current_letter != $old_letter)
{
echo "$current_letter<br /><hr>\n";
$old_letter = $current_letter;
}
echo $row['name'] . '<br />';
}
Untested... adapt to your needs. Oh, add in your "go to top" link, also.
---John W. Holmes...
Amazon Wishlist: http://www.amazon.com/o/registry/3BEXC84AB3A5E
PHP Architect - A monthly magazine for PHP Professionals. Get your copy
today. http://www.phparch.com/