解析Json并在php中获得结果

时间:2018-01-29 14:31:35

标签: php json jsondecoder

我有一个json数据我试图从json获得经度和纬度。

这是JSON代码

{
"0": {
    "provider": "gps",
    "time": 1517235370666,
    "latitude": 31.501278877258,
    "longitude": 74.366261959076,
    "accuracy": 63,
    "speed": 2.1400001049042,
    "altitude": 181,
    "bearing": 28.125,
    "locationProvider": 0
    }
}

我想要纬度和经度。我用json_decode解析它,但我仍然无法得到它。
解析之后

 stdClass Object
(
[0] => stdClass Object
    (
        [provider] => gps
        [time] => 1517235370666
        [latitude] => 31.501278877258
        [longitude] => 74.366261959076
        [accuracy] => 63
        [speed] => 2.1400001049042
        [altitude] => 181
        [bearing] => 28.125
        [locationProvider] => 0
    )
)

1 个答案:

答案 0 :(得分:3)

试试这个

$a = '{
"0": {
    "provider": "gps",
    "time": 1517235370666,
    "latitude": 31.501278877258,
    "longitude": 74.366261959076,
    "accuracy": 63,
    "speed": 2.1400001049042,
    "altitude": 181,
    "bearing": 28.125,
    "locationProvider": 0
    }
}';

$b = json_decode($a); // returns object
print_r($b->{'0'}->{'latitude'}); // to get latitude value

 $c = json_decode($a,true); // returns array
 print_r($c[0]['latitude']); // to get latitude value