dsxon40042 2014-02-20 02:13
浏览 251

如何按字母顺序对mysql结果进行分组?

Looking to list mysql result in json. Needs to be alphabetical

json needs to be like this:

[
  {
    "letter": "A",
    "result": [
      {
        "name": "A&W"
      }
    ]
  },
  {
    "letter": "B",
    "result": [
      {
        "name": "Best Buy "
      }
    ]
  }
]

Need to group mysql results and add them under "result" for the appropriate letter. Based on the first letter of the "name" column in mysql.

heres my code:

    $sql = "SELECT name AS nameletter FROM stores ORDER BY FirstLetter";


    $result = mysql_query($sql);

 while($data = mysql_fetch_assoc($result)){

       echo $data['name'];

    }

--

  • 写回答

2条回答 默认 最新

  • douxu0550 2014-02-20 02:35
    关注

    You can always substr the first letter of the name and then use that to order your query.

    SELECT name, SUBSTR(name, 1, 1) FirstLetter AS nameletter FROM stores ORDER BY FirstLetter
    

    So this will return something like

    Jason, J
    Henry, H
    Harry, H
    Larry, L
    Lenny, L
    

    In PHP you need to build the array of these values, then you should be fairly easily able to loop through the array and get out the names per letter.

    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?