Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

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!

like image 343
user2747609 Avatar asked Sep 24 '13 16:09

user2747609


2 Answers

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'];
like image 103
Amal Murali Avatar answered Oct 24 '22 18:10

Amal Murali


That´s not how you access arrays in PHP

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

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

For your example:

echo $arr['data']['current_condition'][0]['temp_F']
like image 1
Ruben Serrate Avatar answered Oct 24 '22 17:10

Ruben Serrate