1

我有一个 php Mysql 查询,它返回一个包含 id、名称、类型、纬度、经度、距离的记录集

我已经搜索了一种将结果编码为 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 作为搜索中心传入 url。

$bearing=getCompassDirection(getBearing($center_lat, $center_lng, $row['Latitude'], $row['Longitude']));

函数“getCompassDirection”有效且有效,但是如何循环遍历 my_sql 结果并将该函数应用于每一行?

4

2 回答 2

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);
于 2013-07-24T17:45:36.853 回答
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_功能,因为它们已过时且已弃用。

于 2013-07-24T17:50:09.917 回答