我有这个JSON数据,想用PHP解码然后插入MySQL数据库:
{
"data": [
{
"location_id": "5786213",
"name": "Nirvana Lagoon Villas Suites & Spa",
"distance": "0.0300528659549801",
"bearing": "east",
"address_obj": {
"street1": "Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141",
"street2": null,
"city": "Beldibi",
"state": "Antalya Province",
"country": "Turkey",
"postalcode": null,
"address_string": "Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141, Beldibi, Kemer Turkey"
}
}
]
}
我正在尝试使用以下PHP代码进行解码,但我没有得到任何结果:
$url = "http://myurl"
$jsondata = file_get_contents($url);
$datatrip = json_decode($jsondata, true);
$advisor_id = $datatrip['data']['location_id'];
$advisor_name = $datatrip['data']['name'];
$distance = $datatrip['data']['distance'];
$bearing = $datatrip['data']['bearing'];
$street1 = $datatrip['data']['address_obj']['street1'];
$street2 = $datatrip['data']['address_obj']['street2'];
$city = $datatrip['data']['address_obj']['city'];
$state = $datatrip['data']['address_obj']['state'];
$country = $datatrip['data']['address_obj']['country'];
$postalcode = $datatrip['data']['address_obj']['postalcode'];
$address_string = $datatrip['data']['address_obj']['address_string'];
print_r()
结果的 json_decode()
:
Array ( [data] => Array ( [0] => Array ( [location_id] => 5786213 [name] => Nirvana Lagoon Villas Suites & Spa [distance] => 0.0300528659549801 [bearing] => east [address_obj] => Array ( [street1] => Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141 [street2] => [city] => Beldibi [state] => Antalya Province [country] => Turkey [postalcode] => [address_string] => Goynuk Mahallesi, Baskomutan Ataturk Caddesi No: 141, Beldibi, Kemer Turkey ) ) ) )
我的方法解码数据有误吗?
答案 0 :(得分:2)
你正好解码它,但在你的JSON中,'data'键实际上是一个对象数组(注意 [ {...} ] )。
因此,要访问它,您需要指定数组键,例如:
$datatrip['data'][0]['address_obj']['postalcode'];
注意那里的[0]。