duangu6431 2013-06-24 12:35
浏览 44
已采纳

如何使用PHP和MySQL按字母顺序和数字方式获取数据?

How can I get data alphabetically letter-wise and numeric-wise using PHP and MySQL?

I want to display my data like this:

**0-9      A             B              C           D               E        **
   1       Apple         Beautiful      Cat         DAD             Ear 
   2       Ant           Ball           Cart        Doll            Eat

Please help me approach this using PHP and MySQL.

<ul>
    <?php include "config.php";
        $sql4 = mysql_query("select * from categories");
        $count = mysql_num_rows($sql4);
        while($rows = mysql_fetch_array($sql4)){
     ?>

<li><?php echo $rows['category_name'] ?></li>
<?php } ?>

</ul>
  • 写回答

2条回答 默认 最新

  • dtc9222 2013-06-24 12:43
    关注

    You could create a 2D array: Let the $result be the mysql_result of your query:

    $data = array();
    while($row = mysql_fetch_assoc($result)) {
      $letter = strtolower(substr($row["category_name"],0,1));
      if(is_numeric($letter)) $letter = "0-9";
      if(!isset($data[$letter])) $data[$letter] = array();
      $data[$letter][] = $row["category_name"];
    }
    

    and then iterate it to produce the table you want:

    foreach($data as $column=>$values) {
      // $column contains the first letter (or 0-9)
      foreach($values as $value) {
        // $value contains category_name
      }
    }
    

    I hope you can finish it from this point, since this site is not supposed to solve all the problem for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算