Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an alphabet in PHP with only some letters depending of names in database

I have a database (SQL) with a lot of names and I'd like to create alphabetical buttons so it's easy to navigate. I've found lots of examples on how to create an alphabet in PHP. However, I want to build an alphabet with only valid letters depending on the names on the database.

For example:

The database lists: Anderson, Beresford, Donovan, Emerson, Graham....

I'd like the alphabet to appear as: A B D E G ...

(Notice that C and F do not appear).

The only way I can think of is to

-select every name in the database, -order by last name -loop one by one, find what the first character is, save it to an array, -loop to the second one, get the first character, see if it already exists in the array and if it does ignore it -do this on and on until I'm left with an array of only unrepeated letters.

Is this the only way? Or am I missing a simpler solution?

Thanks in advance.

like image 341
cesarcarlos Avatar asked Dec 29 '25 19:12

cesarcarlos


2 Answers

SELECT DISTINCT SUBSTRING(lastname,1,1) 'initial'
FROM people
ORDER BY initial ASC

Bear in mind that this is a string operation on every row in the database, followed by an unindexed sort operation. It will not perform well at all once the table becomes large.

like image 55
Sammitch Avatar answered Dec 31 '25 09:12

Sammitch


SELECT LEFT(name, 1) AS firstletter 
FROM database 
GROUP BY firstletter
ORDER BY last_name 

Works for me.

like image 24
Frederik Spang Avatar answered Dec 31 '25 07:12

Frederik Spang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!