dsbm49845
2016-10-19 13:55
浏览 158

在MySQL中获取行并返回JSON

I have the following SQL statement. "SELECT * FROM table"

Than I do: echo json_encode(mysqli_fetch_all($query));

Which gives me a json like this:

[
  [
    "32",
    "John",
    "12346",
    "email@gmail.com",
  ]
]

This is all fine, but it's missing the field names.

How could I get a JSON like this:

[
  [
    "id" : "32",
    "name" : "John",
    "phone" : "12346",
    "email" : "email@gmail.com",
  ]
]

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我有以下SQL语句。 “SELECT * FROM table”

比我做的: echo json_encode(mysqli_fetch_all($ query)); \ n

这给了我一个像这样的json:

  [
 [
“32”,
“John”,
“12346”,  
“email@gmail.com”,
] 
] 
   
 
 

这一切都很好,但缺少字段名称。 \ n

我怎么能得到这样的JSON:

  [
 [
“id”:“32”,
“name”:“ 约翰“,
”电话“:”12346“,
”电子邮件“:”email@gmail.com“,
] 
] 
   
 
 

谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douchui1488 2016-10-19 13:58
    已采纳

    it seems you get only numeric indizes. try fetching your data as associative array:

    echo json_encode(mysqli_fetch_all($query, MYSQLI_ASSOC));
    

    see also the manual

    已采纳该答案
    打赏 评论
  • drzbc6003 2016-10-19 14:00

    try echo json_encode(mysqli_fetch_all($query, MYSQLI_ASSOC));

    Docu: http://php.net/manual/en/mysqli-result.fetch-assoc.php

    PS: More sophisticated would be to use ORM helper like http://propelorm.org ... saves you a lot of headaches and helps to build maintainable code.

    打赏 评论

相关推荐 更多相似问题