2014-01-12 43 views
0

我目前使用的是第三方API。我有一些diffulties格式化我的db值到json对象中。如果它们处于特定格式,api会接受这些值。在下面的php代码中,我使用foreach循环来获取结果。然后array_push将值放入数组中。我收到字符串数据而不是数字coordinates。最后,我没有得到理想的结果。我如何格式化json对象,使其看起来像下面的例子?PHP的JSON编码 - 对JSON格式特定对象

当前结果:

{ 
coordinates: [ 
"-121.2808, 38.3320" 
], 
attributes: "Sacramento" 
}, 

所需的结果:

{ 
    coordinates: [-121.2808, 38.3320], 
    attributes: { 
     name: 'Sacramento' 
    } 
}, 

PHP循环和json_encode

header("Content-type: application/json"); 
//get the course list 
$location_query = $db_con->prepare("SELECT city, X(location) as latitude, Y(location) as longitude 
FROM company 
"); 
$location_query->execute(); 
$data = $location_query->fetchAll(); 
$output = array(); 
foreach ($data as $row) { 
    array_push($output, array('coordinates'=>array($row["latitude"].",".$row["longitude"]), 'attributes'=>$row["city"])); 


}// foreach ($data as $row) { 
echo json_encode($output); 

回答

5

你需要得到该字符串的浮点表示,尝试使用或者floatval或将它铸造成漂浮物。

floatval

floatval($row["latitude"]) 

铸造

(float) $row["latitude"] 

这样做对经度和纬度。

而且由于某种原因,你是建设有它一个逗号的字符串。为了产生正确的表示,它应该看起来像这样。

array_push($output, array(
    'coordinates' => array((float) $row["latitude"], (float) $row["longitude"]), 
    'attributes' => array('name' => $row["city"])) 
)); 

带键的数组表示对象,因此该数组具有键值>值。

编辑:感谢迈克指出属性错误,太专注于铸造:)

+2

关闭。你需要''attributes'=> array('name'=> $ row [“city”]))' – Mike

+0

@Mike谢谢! :) – SamV

+0

谢谢!现在它是有道理的。我会用float。 – techAddict82