0

目前我正在使用以下代码来获取按名称开头字母排序的数据,如果您运行此代码,您将得到我想要创建的内容

<?php 


$dirs = array('Aname1','Aname2','Aname3','A Nmae','Bname ','Cname','Cardiff','Dname','Dname',);
$cur_let = null;
foreach ($dirs as $dir) {
if ($cur_let !== strtoupper(substr($dir,0,1))){
$cur_let = strtoupper(substr($dir,0,1));
echo "<li class=\"title\">".$cur_let."</li>";
}

echo "<li class=\"clear\">



<div class=\"name\">".$dir."</div>
<div class=\"mobile\"></div>
<div  class=\"telephone\"></div>
<div  class=\"email\"></div>
<div  class=\"action\">edit | delete</div>



<div class=\"clear\"></div>


</li>";


} 

但是如何在下面使用上面的循环从数据库中获取值,它应该显示为(我想突出显示第一个字母)http://i.stack.imgur.com/bLHVD.jpg

$query = "SELECT * FROM phone_number"; 

$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result)){
    $names =  $row['name'].",";

    }
    ?>
4

2 回答 2

1

使用 MySQLi:

$last_letter = null;

$query = "SELECT name FROM phone_number ORDER BY name";
$sql = $mysqli->query($query);
while($row = $sql->fetch_assoc()) {
  $first_letter = substr(ucfirst($row['name']), 0, 1);
  if($last_letter != $first_letter) {
    $last_letter = $first_letter;
    echo '<div class="letter">', $first_letter, '</div>';
  }

  echo ucwords($row['name']), '<br />';

}

mysql_* 不推荐使用的功能:

$last_letter = null;

$query = "SELECT name FROM phone_number ORDER BY name";
$sql = mysql_query($query);
while($row = mysql_fetch_array($sql)) {
  $first_letter = substr(ucfirst($row['name']), 0, 1);
  if($last_letter != $first_letter) {
    $last_letter = $first_letter;
    echo '<div class="letter">', $first_letter, '</div>';
  }

  echo ucwords($row['name']), '<br />';

}
于 2013-01-14T13:36:42.587 回答
0

尝试这样的事情:

$query = "SELECT * FROM phone_number ORDER BY name DESC";
$result = mysql_query($query) or die(mysql_error());

$lastLetter = '';
$html = '<ul>';
while ($row = mysql_fetch_array($result)) {
    $name = $row['name'];
    if (strtoupper($name[0]) !== $lastLetter) {
        if ($lastLetter !== '')
            $html .= '</ul></li>';
        $lastLetter = strtoupper($name[0]);
        $html .= '<li class="title">' . $lastLetter;
        $html .= '<ul>';
    }
    $html .= '<li>' . $name . '</li>';
}
$html .= '</ul></li></ul>';
于 2013-01-14T13:31:26.307 回答