PHP和嵌套JSON:如何访问此元素?

问题描述:

这是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',但它不起作用.我不知道我在做什么错.我走了这么远:

I'm trying to echo 'temp_F' and it is not working. I can't figure out what I'm doing wrong. I get this far:

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

这就是所有失败的地方.我已经完成了var_dump,所以我知道数据在那里.但是我尝试过的每一次回声"尝试都只会在屏幕上显示数组".我尝试了以下多种变体:

And that's where it all fails. I've done var_dump's so I know the data is there. But every 'echo' attempt I've tried only results in 'Array' being displayed to the screen. I've tried many variations of the following:

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

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

Can someone tell me what I'm doing wrong? Thanks!

json_decode() TRUE作为第二个参数为您提供了一个关联数组.但是您当前正在尝试将其作为对象进行访问.

json_decode() with TRUE as second parameter gives you an associative array. But you're currently trying to access it as an object.

请尝试以下操作:

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