在PHP中打印和解析JSON变量

时间:2016-03-31 12:08:56

标签: php json parsing

我有以下带有JSON变量的PHP代码......

$route_geometry_json = "{
    \"route_geometry\": [
        [44.911537, 7.671326],
        [44.911481, 7.671462],
        [44.911455, 7.671531],
        [44.911434, 7.671602],
        [44.911358, 7.671859],
        [44.911273, 7.672175],
        [44.911198, 7.672458],
        [44.91113, 7.672617],
        [44.911069, 7.67275],
        [44.911003, 7.672821],
        [44.910945, 7.672881],
        [44.910869, 7.672954],
        [44.910868, 7.673046],
        [44.91091, 7.673109],
        [44.91095, 7.67319],
        [44.910964, 7.673266],
        [44.910958, 7.673407],
        [44.910955, 7.6735],
        [44.910947, 7.673632],
        [44.910922, 7.673871],
        [44.910828, 7.674786],
        [44.910711, 7.675816],
        [44.910606, 7.676364],
        [44.910467, 7.676322],
        [44.910368, 7.676308],
        [44.910051, 7.676253],
        [44.9097, 7.676162],
        [44.90944, 7.676041],
        [44.909297, 7.675958],
        [44.909174, 7.67583],
        [44.909107, 7.675722],
        [44.908993, 7.675583],
        [44.908758, 7.675448],
        [44.90796, 7.675037]
    ]
  }";

print "Route geometry -->" + json_encode($route_geometry_json);

打印返回“ 0 ”:任何建议/示例?

我也想提取/打印像

这样的伴侣
    44.908993, 7.675583
    44.908758, 7.675448

任何建议都将受到赞赏......

由于

切萨雷

2 个答案:

答案 0 :(得分:1)

您需要print_r(json_decode($route_geometry_json)) json_encode

json_encode用于创建JSON字符串。但由于您已经拥有JSON字符串,因此需要对其进行解码以使其成为数组/对象。

<强>更新

您的要求

echo "Route geometry -->"; 
print_r(json_decode($route_geometry_json));

您无法连结StringObject,因此您收到了Parse错误。

答案 1 :(得分:1)

使用此代码:

$route_geometry = json_decode($route_geometry_json);

foreach ($route_geometry->route_geometry as $value) {
    echo $value[0].', '.$value[1].'<br />';
}