Php 从SQL结果集创建更复杂的json对象
您好,我正在从sql返回一些数据,并希望将其格式化为Json。我知道我可以使用Json.encode(),但数据有点嵌套,我不确定如何实现这一点 这就是我希望json的外观Php 从SQL结果集创建更复杂的json对象,php,arrays,json,Php,Arrays,Json,您好,我正在从sql返回一些数据,并希望将其格式化为Json。我知道我可以使用Json.encode(),但数据有点嵌套,我不确定如何实现这一点 这就是我希望json的外观 [ {"coords": {"lat":53.745,"lng":-0.338}, "iconImage":"https://developers.google.com/maps/documentation/javascript/examples/full/images
[
{"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>"}
]
[
{“协调”:
{“lat”:53.745,“lng”:-0.338},
“图像”:https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
“内容”:“Tony G”},
{“coords”:{“lat”:53.747,“lng”:-0.340},
“图像”:https://maps.gstatic.com/mapfiles/ms2/micons/blue.png",
“内容”:“fred”}
]
这是到目前为止我的代码
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) ;
require(“../PHP/phpsqlajax_dbinfo.PHP”);
$connection=odbc\u connect($database、$username、$password);
//选择测试语句
$query=“选择53.745作为lat,-0.338作为lng,”https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png“作为我的形象,'托尼G'作为内容联盟所有人”
选择53.745作为lat,-0.310作为lng,'https://maps.gstatic.com/mapfiles/ms2/micons/blue.png'作为图像,'弗雷德'作为内容';
$result=odbc\u exec($connection,$query);
//处理结果并创建JSON
while(odbc_fetch_行($result)){
//我在这里干什么?
}
echo json_encode(//我想返回的数据);
感谢您的帮助只需添加到数组,然后编码:
$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);
只需添加到数组中,然后编码:
$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);