【问题标题】:Php json encode - specific format for json objectsPhp json encode - json 对象的特定格式
【发布时间】:2014-01-12 00:15:56
【问题描述】:

我目前正在使用第三方 api。我在将我的 db 值格式化为 json 对象时遇到了一些困难。如果它们采用某种格式,则 api 会采用这些值。在下面的 php 代码中,我使用 foreach 循环来获取结果。然后array_push 将值放入数组中。我正在获取coordinates 的字符串数据而不是数字。最后,我没有得到想要的结果。如何将 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);

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您需要获取该字符串的浮点表示,尝试使用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"]))
    ));
    

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

    编辑:感谢 Mike 指出属性错误,过于专注于选角 :)

    【讨论】:

    • 关闭。你需要'attributes'=> array('name' => $row["city"]))
    • 谢谢!现在它是有道理的。我将使用浮动。
    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2016-10-22
    • 1970-01-01
    • 2022-11-15
    • 2017-06-12
    相关资源
    最近更新 更多