문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top