我正在使用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"
}
]
Run Code Online (Sandbox Code Playgroud)
为什么我得到这种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();
?>
Run Code Online (Sandbox Code Playgroud)
mysql_fetch_array 包括数字索引键和列名索引键.
将其更改为mysql_fetch_assoc,您将获得所需的最终结果.
但请注意,不推荐使用整个mysql扩展,您应该考虑切换到PDO或Mysqli.