简体   繁体   English

PHP JSON编码-JSON对象的特定格式

[英]Php json encode - specific format for json objects

I am currently using a third party api. 我目前正在使用第三方api。 I am having some diffulties formatting my db values into json objects. 我在将db值格式化为json对象时有些困难。 The api takes the values on if they're in a certain format. 如果它们采用某种格式,则api会接受这些值。 In the php code below I am using foreach loop to fetch the results. 在下面的php代码中,我正在使用foreach循环来获取结果。 Then array_push to place the values inside the array. 然后array_push将值放置在数组内。 I am getting string data instead of numerical for coordinates . 我正在获取字符串数据而不是数字作为coordinates In the end, I am not getting the desired result. 最后,我没有得到理想的结果。 How can I format the json objects to look like the example below? 如何格式化json对象,使其看起来像下面的示例?

Current Result: 当前结果:

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

Desired Result: 所需结果:

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

PHP loop and json_encode 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);

You need to get the float representation of that string, try using either floatval or casting it to a float. 您需要获取该字符串的float表示形式,尝试使用floatval或将其强制转换为float。

floatval

floatval($row["latitude"])

Casting 铸件

(float) $row["latitude"]

Do this for both latitude and longitude. 对纬度和经度都执行此操作。

Also for some reason you are building a string with a comma in it. 同样由于某种原因,您正在构建一个带有逗号的字符串。 To produce the proper representation it should look like this. 为了产生正确的表示,它应该看起来像这样。

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

Arrays with keys represent objects, hence the array with a key => value. 带键的数组表示对象,因此带键=>值的数组。

Edit : Thanks to Mike for pointing out the attribute error, was too focused on the casting :) 编辑 :感谢迈克指出属性错误,太过专注于转换:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM