【问题标题】:How can I access the name value in nested JSON using PHP? [duplicate]如何使用 PHP 访问嵌套 JSON 中的名称值? [复制]
【发布时间】:2017-05-30 21:08:51
【问题描述】:

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}}

PHP:

$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 调用:http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Tirana

【问题讨论】:

  • json_decode($response捕获到局部变量,然后解析json怎么样?
  • 位置是一维数组,不是多维数组。所以删除[0] -> echo $response->location->name;
  • 只是一个想法:您不应该提供包含有效 API 密钥的链接,即使基本服务是免费的。但是,您应该将该密钥换成新的。 (而且,由于密钥嵌入在 URL 中,您将来应该使用 HTTPS)

标签: php arrays json


【解决方案1】:

这样试试。你得到json格式的内容。使用json_decode()和第二个参数true转换成数组。

<?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'];

?>

【讨论】:

    【解决方案2】:

    使用json_decode将json字符串解析为数组,然后通过索引访问。

    the demo

    $response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
    $array = json_decode($response, true); 
    echo $array['location']['name']; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多