Chris Chris - 1 year ago 101
JSON Question

from json array with brackets to variable or mysql

I have this script to display some value from a json file:

//read the json file contents
$jsondata = file_get_contents('');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the weather details
$icon = $data['weather']['icon'];
//Display variables
echo "icon value: $icon"; ?>

the json file is :

{"coord":{"lon":130.84,"lat":-12.46},"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10n"}],"base":"stations","main":{"temp":21,"pressure":1011,"humidity":100,"temp_min":21,"temp_max":21},"visibility":5000,"wind":{"speed":1.5,"deg":130},"clouds":{"all":90},"dt":1479589200,"sys":{"type":1,"id":8209,"message":0.162,"country":"AU","sunrise":1479501624,"sunset":1479547451},"id":2073124,"name":"Darwin","cod":200}

I need to display the icon value (10n), but my script didn't work... Brackets in weather section give me some trouble...

thanks for your help

Answer Source

you should access this way

$icon = $data['weather'][0]['icon'];
//Display variables
echo "icon value: $icon"; ?>


icon value: 10n

var_dump will help you to understand structure of array.this is how $data['weather'] looks like.

array (size=1)
  0 => // you forget to access this element first?
    array (size=4)
      'id' => int 501
      'main' => string 'Rain' (length=4)
      'description' => string 'moderate rain' (length=13)
      'icon' => string '10n' (length=3)

weather is a you should access nth element this case first index $data['weather'][0] then you can access icon

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download