Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Works for me.

If your names hav already been pulled into an array you can use something like this (quick and dirty, maybe overkill for what you want/need, but works!)...

<?php

$names = array('Anderson','Beresford','Donovan','Emerson','Graham');

$alphabet = array();
$previous_letter = '';

foreach($names as $value) {
  if($value[0] != $previous_letter) {
    $alphabet[] = $previous_letter = $value[0];
  }
}

print_r($alphabet);

?>

Working example here: http://3v4l.org/VT0Rt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top