PHP 并将 MySQL 行封装到 JSON 数组中

标签 php mysql sql json

我正在玩一个留言簿/聊天室的想法,并且有一个包含三列的 MySQL 表设置:

1 - id - 主键自增

2 - 名称 - 字符串

3 - 注释 - 字符串

我对 PHP 的经验很少,但这是我为这个操作准备的:

$result = mysql_query("SELECT * FROM guestbook");
$i = 0;
while($row = mysql_fetch_array($result))
  {
      //add the row to the $chat array at specific index of $i
      $chat[$i] = $row;
      $i += 1;
  }

$encode = json_encode($chat);
echo "$encode";

但是,这个输出看起来很糟糕:

[{"0":"1","id":"1","1":"Justin ","name":"Justin ","2":"Comment 1","comment":"Comment 1"},
{"0":"2","id":"2","1":"Justin ","name":"Justin ","2":"Another comment","comment":"Another comment"},
{"0":"3","id":"3","1":"Justin ","name":"Justin ","2":"Look at this comment!","comment":"Look at this comment!"},
{"0":"4","id":"4","1":"Justin ","name":"Justin ","2":"Ok I'm done talking","comment":"Ok I'm done talking"}]

我希望获得三个字段:id、name 和 comment,但看起来事情翻了一番。谁能帮忙?

谢谢!

最佳答案

套用 Marc 的话,只需替换这一行:

while($row = mysql_fetch_array($result))

有了这个:

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

为了获得更清晰的 JSON。默认情况下,mysql_fetch_array() 将返回整数索引和关联索引,您只需要关联索引。

关于PHP 并将 MySQL 行封装到 JSON 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7985371/

相关文章:

php - 仅返回字符串开头的大写字母的函数?

mysql - 跳过慢查询日志

sql - 检索 CLOB 字段期间出现 DB2 查询错误

mysql - 在多行上使用多个 IN 子句进行查询

php - 仅选择当前日期或 future 日期的所有内容

php - 在 zend db 中检索最后插入的 user_id

php - wordpress Wp_query 和日期字段的元查询问题

php - Codeigniter SQL 查询构建

php - 从错误的表中选择ID并优化mysql查询

php - 需要适本地在 CSV 中标题标题,而不是使用表列标题