嗨,我要从sql返回一些数据,并想将其格式化为Json,我知道我可以使用json.encode(),但是数据有点嵌套,我不确定如何实现。
这就是我希望json看起来的样子。
[
{"coords":
{"lat":53.745,"lng":-0.338},
"iconImage":"https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
"content":"<h1>Tony G</h1>"},
{"coords":{"lat":53.747,"lng":-0.340},
"iconImage":"https://maps.gstatic.com/mapfiles/ms2/micons/blue.png",
"content":"<h1>fred</h1>"}
]
到目前为止,这是我的代码。
require("../PHP/phpsqlajax_dbinfo.php");
$connection=odbc_connect($database, $username, $password);
//Select Test statement
$query="select 53.745 as lat,-0.338 as lng,'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png' as iconImage, '<h1>Tony G</h1>' as content union all
select 53.745 as lat,-0.310 as lng,'https://maps.gstatic.com/mapfiles/ms2/micons/blue.png' as iconImage, '<h1>fred</h1>' as content ";
$result=odbc_exec($connection,$query);
//work through result and create JSON
while (odbc_fetch_row($result)){
//what do I do here?
}
echo json_encode(//theData I would like to return) ;
感谢您的帮助
答案 0 :(得分:2)
只需添加到数组然后编码:
$json = [];
while ($row = odbc_fetch_row($result)){
$json[] = [
'coords' => ['lat' => $row['lat'],'lng' => $row['lng']],
'iconImage' => $row['iconImage'],
'content' => $row['content'],
];
}
echo json_encode($json);