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!
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";
}
?>
$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
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