我有一个php Mysql查询,它返回一个包含id,Name,Type,Latitude,Longitude,Distance的记录集
我已经搜索了将结果编码为json的解决方案,但所有示例都显示数组被视为一个整体。
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['markers'][]=$row;
}
}
echo json_encode($json);
哪个工作正常并生成以下json:
{"markers":[
["2110","AP","Nans Sous Sainte Anne","46.976810","5.998910","1.60316506124051","0","0","0"],
["3484","AC","Salins Les Bains","46.946568","5.878649","6.8092722205639","0","0","0"], ["2136","AC","Levier","46.959862","6.132840","6.8490368219444","0","1","0"],
["3472","APN","Salins Les Bains","46.936852","5.876290","7.28462233818928","0","0","0"],["3466","ASN","Salins Les Bains","46.932541","5.878990","7.36798013180542","0","2","0"],["2158","FP","Domaine d'Esprits","47.035751","5.824800","8.6152043630634","0","0","0"]]}
但我想要做的是循环每一行并使用函数中的纬度和经度来使用以下函数获取方位; $ center_lat和$ center_lng作为搜索中心在网址中传递。
$bearing=getCompassDirection(getBearing($center_lat, $center_lng, $row['Latitude'], $row['Longitude']));
函数'getCompassDirection'有效且有效,但如何循环my_sql结果并将函数应用于每一行?
答案 0 :(得分:1)
你可以用这个
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$row['bearing']=getCompassDirection(getBearing($center_lat, $center_lng, $row['Latitude'], $row['Longitude']));
$json['markers'][]=$row;
}
}
echo json_encode($json);
答案 1 :(得分:1)
好的,这是你的代码:
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['markers'][]=$row;
}
}
每个$row
都是数字索引数组。
据我所知,您当前的数据是指数 3 的项目,而经度是指数 4 的项目(反之亦然)。所以,你可以改变你的代码:
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$row[] = getCompassDirection(getBearing($center_lat, $center_lng, $row[3], $row[4]));
$json['markers'][]=$row;
}
}
或者您可以使用mysql_fetch_assoc
代替。在这种情况下,您的结果json将具有不同的结构。
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
// check out keys names for lattitude and longtitude first
$row['bearing'] = getCompassDirection(getBearing($center_lat, $center_lng, $row['lattitude'], $row['longtitude']));
$json['markers'][]=$row;
}
}
最后 - 停止使用mysql_
函数,因为它们已过期并已弃用。