如何为JSON编码格式化动态数组?

时间:2018-04-04 19:11:56

标签: php arrays json

我正在尝试为纬度和经度坐标(Google地图)创建一个JSON对象。我希望格式显示如下:

{"restaurants":[
{"lat":-84.9834,"lng":85.8374},
{"lat":-84.8378,"lng":85.8374},
{"lat":-84.7384,"lng":85.3784}
]  
}

这是我到目前为止的代码:

<?php
try{

$conn = new PDO('mysql:host=localhost;dbname=dining','root','mypasswordhere');

}catch(PDOException $e){

   die($e);

}

$qry = "SELECT dining_lat, dining_long FROM dining_listings";
$getData = $conn->query($qry);
$latlngs = array();

while($row = $getData->fetchObject()){
   $myObj->lat = $row->dining_lat;
   $myObj->lng = $row->dining_long;
   $latlngs[] = json_encode($myObj);
}



?>

2 个答案:

答案 0 :(得分:2)

您不想在循环中进行编码,只需创建一个对象数组然后进行编码即可。您可以在查询中使用别名来重命名属性:

$qry = "SELECT dining_lat AS lat, dining_long AS lng FROM dining_listings";

然后:

while($latlngs['restaurants'][] = $getData->fetchObject()){ }   
$latlngs = json_encode($latlngs);

或使用现有查询:

while($row = $getData->fetchObject()){
   $latlngs['restaurants'][] = array('lat' => $row->dining_lat,
                                     'lng' => $row->dining_long);
}
$latlngs = json_encode($latlngs);

或没有循环(需要在查询中使用别名):

$qry = "SELECT dining_lat AS lat, dining_long AS lng FROM dining_listings";

然后:

$latlngs['restaurants'] = $getData->fetchAll();
$latlngs = json_encode($latlngs);

答案 1 :(得分:0)

如果你正好使用fetchAll,你就不会浪费你的时间。以下是我认为应该有效的方法:

<?php
    //Other stuff

    //$results should be an array of what you want now.
    $results = $getData->fetchAll();

    //If you really want the root "restaurants"
    $json = json_encode(["restaurants" => $results]);

?>