dongxia2068 2016-11-20 15:15
浏览 67
已采纳

从带有括号的json数组到变量或mysql

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

<?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"; ?>

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

  • 写回答

1条回答 默认 最新

  • dongshun7312 2016-11-20 15:20
    关注

    you should access this way

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

    output

    icon value: 10n
    

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!