9

名前、電子メール、電話など、メンバーに関するすべての詳細を保存しているメンバーテーブルがあります。名前をアルファベット順のグループとして表示したいです。例に示すように。

A
  Alan
  Alex
  Amar
  Andy

B
  Bob
  Brad

C
  Calvin
  Clerk
D

E

ASC による順序を使用してフィールドをアルファベット順に並べ替えることができますが、アルファベットのグループでそれらを取得するにはどうすればよいですか。

どんな提案でも大歓迎です。私はphpを使用しています。

4

5 に答える 5

2

これを行いたい場合は、SQL 内で;

SELECT SUBSTRING(name, 1, 1) as alpha, name from 'user' GROUP BY SUBSTRING(name, 0, 2), name order by 'alpha', 'name'

そしてphpで

 <?php

    $temp = array(); // would also generate a dynamic array
    $result = mysql_query("SELECT SUBSTRING(name, 1, 1) as alpha, name from 'user' GROUP BY SUBSTRING(name, 0, 2), name order by 'alpha', 'name'"
    while ($row = mysql_fetch_array($result)) {
        $temp[$row['alpha']][] = $row['name'];
    }

    /* this would create array such as;

    'A'
        --> 'Adam'
        --> 'Apple' 
    'B'
        --> 'Ba...'
        --> 'Be...' 
    */

?>

お役に立てれば。

于 2013-07-16T10:33:55.267 に答える
1

この質問には答えが必要です - How to display an Array under alphabetical letters using PHP?

選択した回答:

$previous = null;
foreach($array as $value) {
    $firstLetter = substr($value, 0, 1);
    if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
    $previous = $firstLetter;

    echo $value."\n";
}
于 2013-07-16T10:16:08.623 に答える
0
try this
/* Get the letter user clicked on and assign it a variable called $sort */
$sort = $_REQUEST['letter'];
/* Let's check if variable $sort is empty. If it is we will create a query to display all customers alphabetically ordered by last name. */
if($sort == ""){
$qry= "SELECT * FROM tbl_customers ORDER BY lastname ASC ";
}else{
/* if varible $sort is not empty we will create a query that sorts out the customers by their last name, and order the selected records ascendingly. */
$qry = "SELECT * FROM tbl_customers WHERE lastname LIKE '$sort%' ORDER BY lastname ASC";
}
/* Notice the use of '%' wilde card in the above query  "LIKE '$sort%'". */
//next step is to execute the query.
$execute = mysql_query($qry) or die(mysql_error());
/* Before we display results let's create our alphabetical navigation. The easiest way to create the navigation is to use character codes and run them through the "for" loop. */
echo "<p>";
for ($i = 65; $i < 91; $i++) {
printf('<a href="%s?letter=%s">%s</a> | ',
$PHP_SELF, chr($i), chr($i));
}
echo "</p>";
/* now we are ready to display the results. Since out tbl_customers table has only three fileds we will display the results in a paragraphs. In the real world you may need to display the results in a table.
To display the results we will use "do while" loop to fetch the results. If no customers are found we will display an error message. */
if(mysql_num_rows($execute)>0){
do{
echo "<p>" .$result['id']. " " .$result['firstname']. " " .$result['lastname']. "</p>";
}while($result = mysql_fetch_assoc($execute));
}else{
echo "<p>No customer found.</p>";
}
于 2013-07-16T10:34:10.527 に答える