我正在玩一个留言簿/聊天室的想法,并且有一个包含三列的 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/