我正在使用PHP处理JSON。我使用json_encode()函数来创建JSON。Hovewer我有奇怪的JSON输出:
[
{
"0": "1",
"1": "test",
"2": "test",
"ID": "1",
"title": "test",
"imageUrl": "test"
},
{
"0": "2",
"1": "welcome",
"2": "http://overkiller.pl/Smokopedia/Images/01.jpg",
"ID": "2",
"title": "welcome",
"imageUrl": "http://overkiller.pl/Smokopedia/Images/01.jpg"
}
]为什么我要得到这样的JSON我的PHP代码:
<?php
header('Content-type: application/json');
$connection = mysql_connect('localhost', 'root', 'sam1');
$array = array();
if($connection)
{
mysql_select_db("Smokopedia");
$result = mysql_query("Select * from mainMenu");
if($result)
{
while ($row = mysql_fetch_array($result))
{
array_push($array, $row);
}
echo json_encode($array);
}else
{
$errorJson = array(
message => 'Result is empty or incorrect',
type => 'error'
);
echo json_encode($errorJson);
}
}
mysql_close();
?>发布于 2014-10-16 12:00:21
mysql_fetch_array包括数值索引键和列名索引键。
将其更改为mysql_fetch_assoc,您将得到所需的最终结果。
但是请注意,整个mysql扩展是不推荐的,您应该考虑切换到PDO或Mysqli。
发布于 2014-10-16 12:00:40
问题是您正在获取一个数组,其中包括数字索引和字符串键。
更改为mysql_fetch_assoc
while ($row = mysql_fetch_ssoc($result)) 附带注意:不推荐使用mysql_*库。考虑升级到现代API,如MySQLi或PDO。
https://stackoverflow.com/questions/26403819
复制相似问题