dpo15099 2014-09-04 01:35
浏览 33
已采纳

PHP循环检测每个MySQL字母结果的第一个实例

If I query a database with PHP using MySQLi, how can I detect the first instance of each letter of the alphabet?

If I have a table like -

ID | name
1    Allen
2    John
3    Sally
4    William

and I query

SELECT * FROM table ORDER BY name ASC

Can I have something in my loop that says "if this is the first time you've seen the string in name start with the letter A", echo <a id="a"></a> to create an anchor tag? Then it will proceed to do the same for B,C,D,E,F,G, etc.. Then I can create an alphabetical legend.

Here is my query and loop:

$query = "SELECT * FROM table ORDER BY name ASC";
$result = $db->query($query);
$num = $result->num_rows;
for($i=0; $i < $num; $i++){
    $row = $result->fetch_object();
      //IF THIS IS THE FIRST TIME SEEING $row->name START 
      //WITH A DIFFERENT LETTER OF THE ALPHABET ECHO SOMETHING...
    echo $row->name;
 }
  • 写回答

2条回答 默认 最新

  • dongxinxin7809 2014-09-04 01:42
    关注

    Create an associative array that records which letters you've seen.

    $letters_seen = array();
    
    while ($row = $result->fetch_object()) {
        $letter = substr($row->name, 0, 1);
        if (!isset($letters_seen[$letter])) {
            // This is the first time seeing this initial letter
            $letters_seen[$letter] = true;
            echo "<a id='$letter'>$letter</a>";
        }
        echo $row->name;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能