简体   繁体   中英

order by alphabet PHP, MySql but list the letter before each group

Say I had a table with:

First      | Last
-------------------
Bob          Dylan
Ashley       Scott
Lol Cats
black cake

It would order them but do

A:
  Ashley Scott
B:
  Bob Dylan
  Black Cake
L:
  lol cats

I know how to list by abc from MySql. but i want to have it put the letter before each group of names. So i can make a nice looking interface, and at the top of the page have AB C D letters at the top that went contacts#letterL

I know how to do the #links in a url. Its just the div Id. I know how to grab from MySql. The part i'm not sure on is echoing the letter before the group of names that start with that letter.

I was thinking of getting the first letter of the name of saving it in a variable.

if ($lastletter == $currentleter) {
  echo name
} else {
  $lastletter = $currentleter;
  echo '<div id="Letter ' . $currentleter .  '" class="letterheader">' . $currentleter . '</div>';
}

Not sure if this idea would be a efficient idea. Would this be the right away of doing this?

Untested code but something like this should work:

$currentleter = substr($name , 0 , 1);
if ($lastletter != $currentleter){
    echo '<div id="Letter' . $currentleter .  '" class="letterheader">' . $currentleter . '</div>';
    $lastletter = $currentleter;
}

echo $name;

You can select the records with order by first name.

$sql = "select * from tblname order by firstname";

$lastletter = "A";

echo $lastLetter;
if ($lastLetter != substr($firstname, 0,1))
echo $lastLetter;

echo $firstname;

This looks like a pretty good solution except IDs must not have spaces in them so you wanna change

<div id="Letter '. $currentleter. '" class="letterheader"> to

<div id="Letter_'. $currentleter. '" class="letterheader"> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM