Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetical listing group by alphabet in php [closed]

Tags:

php

mysql

I have a member table where I am storing all details about a member including its name, email, phone etc. I want the name will appear as a alphabetical group wise. Such as shown in example.

A
  Alan
  Alex
  Amar
  Andy

B
  Bob
  Brad

C
  Calvin
  Clerk
D

E

I can sort the field alphabetically using order by ASC but how do I get them in group of alphabet.

Any suggestions are most welcome. I am using php.

like image 210
Amar Banerjee Avatar asked Jul 16 '13 09:07

Amar Banerjee


2 Answers

Maybe it is a bad way to do it, but it can help you now.

<?php

    $aGroup = array(
        "A" => array(),
        "B" => array(),
        "C" => array(),
        "D" => array(),
        "E" => array(),
        // until "Z"
        );

    $result = mysql_query("SQL as you want");

    while ($row = mysql_fetch_array($result)) {
        $letter = strtoupper($row[0][0]); // I supose that the first column is the name
        $aGroup[$letter][] = $row;
    }

?>
like image 84
Lompa Avatar answered Sep 30 '22 11:09

Lompa


If you want to do this, within your SQL;

SELECT SUBSTRING(name, 1, 1) as alpha, name from 'user' GROUP BY SUBSTRING(name, 0, 2), name order by 'alpha', 'name'

and in php

 <?php

    $temp = array(); // would also generate a dynamic array
    $result = mysql_query("SELECT SUBSTRING(name, 1, 1) as alpha, name from 'user' GROUP BY SUBSTRING(name, 0, 2), name order by 'alpha', 'name'"
    while ($row = mysql_fetch_array($result)) {
        $temp[$row['alpha']][] = $row['name'];
    }

    /* this would create array such as;

    'A'
        --> 'Adam'
        --> 'Apple' 
    'B'
        --> 'Ba...'
        --> 'Be...' 
    */

?>

Hope this helps.

like image 27
WattoWatto Avatar answered Sep 30 '22 11:09

WattoWatto