我正在创建一个从SQL数据库中提取数据的应用程序。我的PHP代码echos json数据,但它没有很好地形成。我当前的输出没有结果数组的名称,我希望它 - 我已经提供了一个链接,指向我希望输出看起来如何。 任何帮助将不胜感激。
<?php
// database settings
$db_username = "****";
$db_password = "****";
$db_name = "****";
$db_host = "****";
//open connection to mysql db
$connection = mysqli_connect("$db_host","$db_username","$db_password","$db_name") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from markers";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$data = array($emparray);
echo json_encode($data);
//close the db connection
mysqli_close($connection);
?>
答案 0 :(得分:1)
如果替换
,该怎么办?$data = array($emparray);
与
$data = array('markers' => $emparray);
应输出类似
的内容JSON : {"markers":[{"id":1,"lorem":"ipsum"},{"id":2,"lorem":"dolor"}]}
php > var_dump($test);
array(1) {
["markers"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
int(1)
["lorem"]=>
string(5) "ipsum"
}
[1]=>
array(2) {
["id"]=>
int(2)
["lorem"]=>
string(5) "dolor"
}
}
}