Listing Alphabetically with Letter Heading

时间:2018-03-22 23:50:00

标签: php mysql

From a database of names, I'm printing out a list of unique surnames with a count of the number of occurrences of each. However, with 500+ unique names the list is painful to read.

How can I group by first letter, like a heading?

Goal:

A  
Adams (53), Adamson (5)...  
B  
Barclay (1), Barton (23)...  
etc               

Code so far:

 $sql = "SELECT surname, COUNT(surname) AS count
          FROM $table
          WHERE first <> 'unknown'
          GROUP BY surname
          ORDER BY surname ASC";

  $result = mysqli_query($conn,$sql);

  while($row = mysqli_fetch_assoc($result)) {  

    $surname = $row["surname"];
    $count = $row["count"];

  echo "<li>".$surname." (".$count."), </li>\n";
}

1 个答案:

答案 0 :(得分:2)

As long as you force the sorting on your SQL query you can track the first letter you see in each surname, and if it's not the currently active first letter, inject a heading purely in PHP:

$html = "<ul>\n";
$first = false;

while($row = mysqli_fetch_assoc($result)) {  
  $surname = $row["surname"];
  $count = $row["count"];

  $index = substr($surname,0,1);
  if ($index != $first) {
    $first = $index;
    $html .= "</ul>\n<h2>$first</h2>\n<ul>";
  }

  $html .= "<li>$surname ($count)</li>\n";
}

$html .= "</ul>";

...

echo $html