如何在循环中使用foreach?

时间:2013-01-14 13:29:07

标签: php mysql foreach

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

<?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>";


} 

但是如何使用上面的循环来从数据库中获取vales并且它应该显示为(我想突出显示第一个字母)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'].",";

    }
    ?>

2 个答案:

答案 0 :(得分: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 />';

}

答案 1 :(得分: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>';