首页 > 解决方案 > json编码的php数组在坐标变量输出周围环绕引号

问题描述

我正在编写一个 wordpress 循环,它获取多个帖子并在基于 php 的数组中输出帖子自定义字段 GeoJson 坐标数组。

请参阅下面的$sFeatureCoordinates变量内容。

  [
    [
      -0.7332730293273926,
      51.89886634382943
    ],
    [
      -0.7326534390449524,
      51.89770778622719
    ],
    [
      -0.7318434119224548,
      51.898079355455344
    ],
    [
      -0.7332730293273926,
      51.89886634382943
    ]
  ]

然后看下面我的 php 数组,然后我用它json_encode来格式化数组。

$arr = [
    'type' => 'FeatureCollection',
    'features' => []
];

// loop through each post
while($oQuery->have_posts()): $oQuery->the_post();

    // grab our type and coordinates
    $sFeatureType = get_field('geojson_feature_type');
    $sFeatureCoordinates = get_field('geojson_feature_coordinates');

    // add this to our features
    $arr['features'][] = [
        'type' => 'Feature',
        'properties' => [
            'id' => get_the_id(),
            'name' => get_the_title()
        ],
        'geometry' => [
            'type' => $sFeatureType,
            'coordinates' => [
                [ preg_replace('/\s+/', '', $sFeatureCoordinates) ]
            ]
        ]
    ];

endwhile;

$json = json_encode($arr);

这是从http://myjson.com/pssis上面的数组输出的我的 json 示例

我遇到的问题是,coordinates当它被编码时,它被包裹在引号中。

当我的谷歌地图脚本尝试读取它时,这会导致 js 错误。

关于如何阻止我的coordinates内容被引号包裹的任何想法json_encode

非常感谢

标签: phpjson

解决方案


$sFeatureCoordinates是 JSON,所以只需将其解码并添加到数组中。然后,当您json_encode. 根据需要添加或删除[ ]以获得正确的嵌套级别:

'coordinates' => [ [ json_decode($sFeatureCoordinates, true) ] ]

推荐阅读