doumu9019 2017-01-08 16:42
浏览 45
已采纳

在不同的标题下按字母顺序对mysql表中的数据进行排序

I'm trying to sort a list of names with allocated links coming from mysql table.
Would like it to look something like this in html:

    <h3>A</h3>
    <ul>
       <li>Andrea</li>
       <li>Arron</li>
    </ul>

So far I was able to list letters and names in alphabetical order, but I don't know how to make a loop that would list all names starting with 'A' under heading 'A' etc.

    <?php

    $connection = mysqli_connect('localhost', 'root', '', 'database');

    $query = "SELECT * FROM users ORDER BY name";
    $result = $connection->query($query);

    $azRange = range('A', 'Z');

    foreach ($azRange as $letter){
        echo "<h3>" . $letter . "</h3>";
    }

    echo "<ul>";

    while($row = $result->fetch_array()){
        echo "<li><a href=\"" . $row['link'] . "\">" . $row['name'] . "</a></li>";
    }

    echo "</ul>";

    ?>

Thank you.

  • 写回答

4条回答 默认 最新

  • dongzhe3171 2017-01-08 16:47
    关注

    You need to check first letter of every $row['name'] and control the change of this letter. So, if first letter was 'A' for several rows, and then it has changed to 'B' - this means that you need to echo this new letter (B).

    echo "<ul>";
    // init first letter with an empty value
    $first_letter = "";
    
    while($row = $result->fetch_array()){
        // get first letter of current name
        $first_letter_of_name = substr($row['name'], 0, 1);
        if ($first_letter_of_name != $first_letter) {
            // first letters differ, this 
            // means that new letter is here
    
            // Echo this new letter
            echo '<li>Letter: <b>' . $first_letter . '</b></li>'
            // Change flag's value
            $first_letter = $first_letter_of_name;
        }
        echo "<li><a href=\"" . $row['link'] . "\">" . $row['name'] . "</a></li>";
    }
    
    echo "</ul>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备