Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

php and nested json: how can i access this element?

Here's the json text:

{
"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"
    }]
}

}

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);

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Try the following:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...