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.
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;
    }
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With