Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group PHP results on first letter of name

Tags:

php

mysql

I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the letter above the group i.e.

A
-----------
Albert
Alfred

C
-----------
Charles

D
-----------
Delta etc...

Thanks!

like image 489
Kelly Brown Avatar asked Jul 20 '11 10:07

Kelly Brown


2 Answers

Order the results by lastname on MySQL side and track the change of the first letter on PHP side:

<?php

$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");

while ($rec = mysql_fetch_assoc($rs)) {
    if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
        $initial = strtoupper(substr($rec['lastname'], 0, 1));
        print "$initial\n";
    }
    print $rec['lastname'] . "\n";
}

?>
like image 141
Quassnoi Avatar answered Oct 22 '22 15:10

Quassnoi


$letter = null;
foreach ($array as $word) {
  if ($letter != $word[0]) {
    $letter = $word[0];
    echo '<b>'.strtoupper($word[0]) . '</b><br/>';
  }
  echo strtoupper($word) . '<br/>';
}

and to tour query add line :

order by `your_field` asc
like image 4
Subdigger Avatar answered Oct 22 '22 15:10

Subdigger