PHP并将MySQL行封装到JSON数组中 [英] PHP and encapsulating MySQL rows into a JSON array
问题描述
我正在玩一个留言簿/聊天室的主意,并设置了一个包含三列的MySQL表:
I'm playing with a guestbook/chatroom idea and have a MySQL table setup with three columns:
1-id-主键自动递增
1 - id - Primary Key auto increment
2-名称-字符串
3-评论-字符串
我对PHP的经验很少,但这是我为此操作汇总的内容:
I have very little experience with PHP but this is what I've put together for this operation:
$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";
但是,此输出看起来很糟糕:
However, output from this looks pretty awful:
[{"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,但看起来好像翻了一番.有人可以帮忙吗?
I was hoping to get three fields: id, name, and comment, but it looks like things doubled. Can anyone help?
谢谢!
推荐答案
释义Marc,只需替换此行:
To paraphrase Marc, Just replace this line:
while($row = mysql_fetch_array($result))
与此:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
获取更清晰的JSON.默认情况下,mysql_fetch_array()
将同时返回整数索引和关联索引,您只需要关联索引.
To get cleaner JSON. By default mysql_fetch_array()
will return both an integer index and an associative index, you only want the associative index.
这篇关于PHP并将MySQL行封装到JSON数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!