我有一个成员表,我在其中存储有关成员的所有详细信息,包括其姓名、电子邮件、电话等。我希望该名称将按字母顺序显示。如示例所示。
A
Alan
Alex
Amar
Andy
B
Bob
Brad
C
Calvin
Clerk
D
E
我可以使用 ASC 的顺序按字母顺序对字段进行排序,但是如何将它们放在字母组中。
任何建议都非常受欢迎。我正在使用 php。
也许这是一个不好的方法,但它现在可以帮助你。
<?php
$aGroup = array(
"A" => array(),
"B" => array(),
"C" => array(),
"D" => array(),
"E" => array(),
// until "Z"
);
$result = mysql_query("SQL as you want");
while ($row = mysql_fetch_array($result)) {
$letter = strtoupper($row[0][0]); // I supose that the first column is the name
$aGroup[$letter][] = $row;
}
?>
如果你想这样做,在你的 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...'
*/
?>
希望这可以帮助。
这个问题应该有答案 -如何使用 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";
}
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>";
}
您可以使用您的选择查询来做到这一点,如下例所示:
$query = "SELECT * FROM `user` ORDER BY `name` ASC ;";