php解析json数据
从来没有这样做过,并且对格式和如何访问特定变量感到困惑。php解析json数据
结果:
$result = json_decode($result);
print_r($result);
是:
stdClass Object
(
[input] => stdClass Object
(
[address_components] => stdClass Object
(
[number] => 1109
[predirectional] => N
[street] => Highland
[suffix] => St
[formatted_street] => N Highland St
[city] => Arlington
[state] => VA
[zip] => 22201
[country] => US
)
[formatted_address] => 1109 N Highland St, Arlington, VA 22201
)
[results] => Array
(
[0] => stdClass Object
(
[address_components] => stdClass Object
(
[number] => 1109
[predirectional] => N
[street] => Highland
[suffix] => St
[formatted_street] => N Highland St
[city] => Arlington
[county] => Arlington County
[state] => VA
[zip] => 22201
[country] => US
)
[formatted_address] => 1109 N Highland St, Arlington, VA 22201
[location] => stdClass Object
(
[lat] => 38.886672
[lng] => -77.094735
)
[accuracy] => 1
[accuracy_type] => rooftop
[source] => Arlington
)
[1] => stdClass Object
(
[address_components] => stdClass Object
(
[number] => 1109
[predirectional] => N
[street] => Highland
[suffix] => St
[formatted_street] => N Highland St
[city] => Arlington
[county] => Arlington County
[state] => VA
[zip] => 22201
[country] => US
)
[formatted_address] => 1109 N Highland St, Arlington, VA 22201
[location] => stdClass Object
(
[lat] => 38.886665
[lng] => -77.094733
)
[accuracy] => 1
[accuracy_type] => rooftop
[source] => Virginia Geographic Information Network (VGIN)
)
)
)
我如何可以访问纬度和经度值?由于混合了对象和数组,因此我感到困惑。我从来没有用这种方式与PHP的JSON合作...这是一个地理编码api,返回JSON格式。
我基本上想要做一些类似$lat = $result['results'][0]['location']['lat'];
等等。
你必须json_decode
使用true
作为第二个参数,以便输出将是正常的PHP数组不stdclass
阵列(这样就可以用你的方法,你正在尝试什么)
所以做象下面这样: -
$result = json_decode($result,true);
echo $lat = $result['results'][0]['location']['lat'];
echo $lng = $result['results'][0]['location']['lng'];
注: -
1.根据您目前的格式,也可以得到数据如下图所示: -
echo $lat = $result->results[0]->location->lat; //using object approach
echo $lng = $result->results[0]->location->lng; //using object approach
2.使用foreach()
让所有lat-lng
记录。
foreach($result->results as $val) { //if using stdclass array
echo "Latitude = ".$val->location->lat;
echo "Longitude = ".$val->location->lng;
}
或者: -
foreach($result['results'] as $val) {//if using normal array
echo "Latitude = ".$val['location']['lat'];
echo "Longitude = ".$val['location']['lng'];
}
知道它是一些简单的我失踪了......这就是我一直在寻找...谢谢! – user756659
@ user756659很高兴帮助你:) :) –
使用第二个参数为转换所有对象数组为真。否则,你可以得到这样的值。
$result->results[0]->location->lat;
$result->results[0]->location->lng;
这是'lng'不''长'。现在+1,因为你也是正确的。 –
您可以从结果存取纬度经度如下
$result = json_decode($result);
echo $result->results[0]->location->lat;
echo $result->results[0]->location->lng;
我可以看到,从你的榜样,你有多个记录来获取。使用foreach()
打印细节
$result = json_decode($result);
foreach($result->results as $value) {
echo "Lat--",$value->location->lat; //using object
echo "Long--",$value->location->lng;
}
使用类型转换,将其转换成对象 –