php json_encode mysql 结果以特定方式

标签 php mysql arrays json

我是 php 文件中 mysql 查询的 json 编码结果。我的php脚本如下:

while ($row = mysql_fetch_array($result)) {
   $to_encode[] = $row;
}
echo json_encode($to_encode);

我的输出

[
  {
    "0": "Variables",
    "topic_name": "Variables",
    "1": "pyt1.1",
    "rdf_id": "pyt1.1",
    "2": "Hello World",
    "ex_name": "Hello World",
    "3": "1",
    "line_number": "1",
    "4": "print (\"Hello World!\")",
    "code": "print (\"Hello World!\")",
    "5": "Some Comment",
    "comment": "Some Comment"
  }
]

在这里,正如您所看到的,每个备用行都是多余的。我不需要第 1、3、5 行...等等。

所需输出

[
  {
    "topic_name": "Variables",
    "rdf_id": "pyt1.1",
    "ex_name": "Hello World",
    "line_number": "1",
    "code": "print (\"Hello World!\")",
    "comment": "Some Comment"
  }
]

如何更改php脚本以获得所需的输出?

最佳答案

在您的情况下,您应该使用 mysql_fetch_array()带有 MYSQL_ASSOC 标志:

while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) )

文档中的重要内容:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.

就像文档中提到的那样,您应该使用 mysqliPDO .

您可以在这里找到更多信息:https://stackoverflow.com/a/8891552/5297359

关于php json_encode mysql 结果以特定方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091414/

相关文章:

php - 将日期时间值从 php 插入 MySQL

php - 在 Laravel 5 中,我们在哪里编写访问数据库的函数?

java - [EBean][PlayFramewrok 2.5] ID 未从数据库加载

c++ - 将 valarray 转换为基本数组

没有实例的PHP匿名类

javascript - 如何通过代码禁用 JWplayer 中的全屏按钮?

c - 打印字符串显示符号

arrays - 将数组中的每个单词大写

java - MySQL 错误 - 不正确的 DOUBLE 值 : 'chests'

MYSQL报错不知道怎么解决