[英]PHP and encapsulating MySQL rows into a JSON array
I'm playing with a guestbook/chatroom idea and have a MySQL table setup with three columns: 我正在玩一个留言簿/聊天室的想法,并且有一个包含三列的MySQL表设置:
1 - id - Primary Key auto increment 1-id-主键自动递增
2 - name - String 2-名称-字符串
3 - comment - string 3-注释-字符串
I have very little experience with PHP but this is what I've put together for this operation: 我对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";
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"}]
I was hoping to get three fields: id, name, and comment, but it looks like things doubled. 我希望获得三个字段:ID,名称和注释,但看起来好像翻了一番。 Can anyone help?
有人可以帮忙吗?
Thanks! 谢谢!
To paraphrase Marc, Just replace this line: 释义Marc,只需替换此行:
while($row = mysql_fetch_array($result))
With this: 有了这个:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
To get cleaner JSON. 为了获得更清洁的JSON。 By default
mysql_fetch_array()
will return both an integer index and an associative index, you only want the associative index. 默认情况下,
mysql_fetch_array()
将同时返回整数索引和关联索引,您只需要关联索引。
mysql_fetch_array returns a compound array: indexed AND keyed. mysql_fetch_array返回一个复合数组:索引和键。 To fetch just one or the other, use
mysql_fetch_row()
(indexed only), mysql_fetch_assoc()
(keyed only), or use the extra argument on fetch_array to specify which you want: mysql_fetch_array($result, MYSQL_BOTH);
要仅获取一个,请使用
mysql_fetch_row()
(仅索引), mysql_fetch_assoc()
(仅键),或在fetch_array上使用额外的参数来指定所需的值: mysql_fetch_array($result, MYSQL_BOTH);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.