Jump to content

[SOLVED] php/mysql alphabetical grouping


Jikson26

Recommended Posts

Hello,

 

I'm trying to code something that will group names together alphabetically.

 

Let's say I have these entries in my MySQL:

 

ID   |   Names
-------------------
1    |   John
2    |   Mike
3    |   Kate
4    |   George
5    |   Sarah
6    |   Selma
7    |   Mick
8    |   Jared

 

 

I want to display the results with headings, something like:

 

G
-------------
George

J
-------------
Jared
John

K
-------------
Kate

M
-------------
Mick
Mike

S
-------------
Sarah
Selma

 

How would I code this?

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/126040-solved-phpmysql-alphabetical-grouping/
Share on other sites

here's one way (uses MySql's sample "world" database)

 

<?php
mysql_connect('localhost');
mysql_select_db('world');

$sql = "SELECT SUBSTRING(name,1,1) as init, 
        GROUP_CONCAT(name ORDER BY name SEPARATOR '<br>')
        FROM country
        GROUP BY init";
$res = mysql_query($sql);
while (list($init, $names) = mysql_fetch_row($res))
{
    echo "$init<br/>---------------------------<br/>$names<br/><br/>";
}  
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.