我正在玩一个留言簿/聊天室的想法,并且有一个包含三列的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,名称和注释,但看起来好像翻了一番。有人可以帮忙吗?
谢谢!
释义Marc,只需替换此行:
while($row = mysql_fetch_array($result))
有了这个:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
为了获得更清洁的JSON。默认情况下mysql_fetch_array()将同时返回整数索引和关联索引,您只需要关联索引。
mysql_fetch_array()