2013-09-24 68 views
5

这里的JSON文本:php和嵌套的json:我如何访问这个元素?

{ 
"data": { 
    "current_condition": [{ 
     "cloudcover": "75", 
     "humidity": "63", 
     "observation_time": "03:41 PM", 
     "precipMM": "0.0", 
     "pressure": "1020", 
     "temp_C": "15", 
     "temp_F": "59", 
     "visibility": "16", 
     "weatherCode": "116", 
     "weatherDesc": [{ 
      "value": "Partly Cloudy" 
     }], 
     "weatherIconUrl": [{ 
      "value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" 
     }], 
     "winddir16Point": "SSE", 
     "winddirDegree": "160", 
     "windspeedKmph": "7", 
     "windspeedMiles": "4" 
    }], 
    "request": [{ 
     "query": "Northville, United States Of America", 
     "type": "City" 
    }], 
    "weather": [{ 
     "date": "2013-09-24", 
     "precipMM": "0.0", 
     "tempMaxC": "20", 
     "tempMaxF": "67", 
     "tempMinC": "8", 
     "tempMinF": "47", 
     "weatherCode": "113", 
     "weatherDesc": [{ 
      "value": "Sunny" 
     }], 
     "weatherIconUrl": [{ 
      "value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" 
     }], 
     "winddir16Point": "ESE", 
     "winddirDegree": "111", 
     "winddirection": "ESE", 
     "windspeedKmph": "10", 
     "windspeedMiles": "6" 
    }] 
} 

}

我想呼应 'temp_F',它是行不通的。我无法弄清楚我做错了什么。我得到这个很远:

$url = file_get_contents("http://blahblahblahblah"); 
$arr = json_decode($url,true); 

而这就是所有失败。我做了var_dump的,所以我知道数据在那里。但是我试过的每个'回声'尝试都只会导致'数组'被显示在屏幕上。我已经尝试了以下的许多变化:

echo $arr->{'data'}->{'current_condition[0]'}->{'temp_F'}; 

有人能告诉我我做错了什么吗?谢谢!

+0

如果您的错误报告被激活,您应该实际看到'尝试获取非对象的属性...'。 – ComFreek

回答

10

json_decode()TRUE作为第二个参数为您提供了一个关联数组。但是你目前正在尝试以对象的形式访问它。

尝试以下操作:

echo $arr['data']['current_condition'][0]['temp_F']; 
0

That's不是如何访问数组在PHP

$array['index']="value"; 

echo $array['index1']['index2'] 

对于示例:

echo $arr['data']['current_condition'][0]['temp_F'] 
0

您可以使用JSON来检索JSON结果的变量,然后使用可变信息显示在JS。

$.ajax({ 
    'type': 'GET', 
    'url': 'abc.com, 
    'dataType': 'json', 
    success: function (data) { 

    var response = data; 
    // alert(response.data.current_condition) //something like that 
    // for (var i = 0; i < response.length; i++) { } 

    }