如何使用PHP访问嵌套JSON中的名称值?
JSON: PHP:如何使用PHP访问嵌套JSON中的名称值?,php,arrays,json,Php,Arrays,Json,JSON: PHP: API调用:使用json_decode将json字符串解析为数组,然后使用索引访问它 $response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris'); var_dump(json_decode($response)); echo $response->location[0]->name;
API调用:使用json_decode将json字符串解析为数组,然后使用索引访问它
$response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
var_dump(json_decode($response));
echo $response->location[0]->name;
尝试这样做。您将获得
json
格式的内容。使用json_decode
()和第二个参数true
将其转换为数组
$response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
$array = json_decode($response, true);
echo $array['location']['name'];
json\u decode($response)捕获一个局部变量,然后解析这个json,怎么样?位置是一个一维数组,而不是多维数组。所以删除[0]
->echo$response->location->name;
只是一个想法:即使基本服务是免费的,也不应该提供包含有效API密钥的链接。但是,您应该将该密钥交换为新的密钥。(而且,由于密钥嵌入URL中,您将来应该使用HTTPS)
$response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
$array = json_decode($response, true);
echo $array['location']['name'];
<?php
$json = '{"location":{"name":"Tirana","region":"Tirane","country":"Albania","lat":41.33,"lon":19.82,"tz_id":"Europe/Tirane","localtime_epoch":1484543668,"localtime":"2017-01-16 5:14"},"current":{"last_updated_epoch":1484543668,"last_updated":"2017-01-16 05:14","temp_c":4.0,"temp_f":39.2,"is_day":0,"condition":{"text":"Overcast","icon":"//cdn.apixu.com/weather/64x64/night/122.png","code":1009},"wind_mph":6.9,"wind_kph":11.2,"wind_degree":150,"wind_dir":"SSE","pressure_mb":1009.0,"pressure_in":30.3,"precip_mm":0.0,"precip_in":0.0,"humidity":60,"cloud":0,"feelslike_c":1.2,"feelslike_f":34.2}}
';
$array = json_decode($json,true);
//print_r($array);
$location = $array['location'];
echo $location['name'];
?>