2016-11-20 113 views
0

我有这样的脚本,以显示从一个JSON文件中的一些值:从JSON阵列括号变量或MySQL

<?php 
//read the json file contents 
$jsondata = file_get_contents('http://website.com/file.json'); 
//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"; ?> 

JSON文件是:

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

我需要显示的图标值(10n),但我的脚本没有工作...在天气部分支架给我一些麻烦...

感谢您的帮助

+1

注意你的数据结构。你有一个数组和对象。 – Quentin

回答

0

你应该访问这样

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

输出

icon value: 10n 

var_dump将帮助您了解array.this的结构是如何$data['weather']样子。

//var_dump($data['weather']); 
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) 

天气是array.so你应该first.in这种情况下,第一指数$data['weather'][0]访问第n个元素,那么你可以访问icon

+0

感谢您的快速帮助!我会阅读关于var_dump的。 – Chris

+0

@Chris var_dump只是转储数据,所以你可以看到很好的结构。它只能用于测试 –