【问题标题】:(PHP) can't get information out of which I think is a multidimensional array received from JSON(PHP) 无法获取我认为是从 JSON 接收的多维数组的信息
【发布时间】:2016-08-02 23:41:37
【问题描述】:

我正在尝试构建一个从 Yahoo API 获取天气的 PHP 脚本。我使用以下方法成功导入了数据:

<?php
     $BASE_URL = "http://query.yahooapis.com/v1/public/yql";
     $yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Amsterdam")';
     $yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";

    // Make call with cURL
    $session = curl_init($yql_query_url);
    curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($session);
    // Convert JSON to PHP object
    $phpObj =  json_decode($json);
    echo '<pre>';print_r($phpObj).'<pre>';

    $weather = json_decode(json_encode($phpObj->query->results->channel->item->forecast), True);

?>

我在使用 print_r 时从 $weather 中得到以下信息:

    Array
        ([0] => Array
            (
                [code] => 12
                [date] => 12 Apr 2016
                [day] => Tue
                [high] => 62
                [low] => 48
                [text] => Rain
            )

        [1] => Array
            (
                [code] => 28
                [date] => 13 Apr 2016
                [day] => Wed
                [high] => 60
                [low] => 46
                [text] => Mostly Cloudy
            )

        [2] => Array
            (
                [code] => 28
                [date] => 14 Apr 2016
                [day] => Thu
                [high] => 61
                [low] => 43
                [text] => Mostly Cloudy
            )

        [3] => Array
            (
                [code] => 47
                [date] => 15 Apr 2016
                [day] => Fri
                [high] => 57
                [low] => 48
                [text] => Scattered Thunderstorms
            )
    )

我想从 [0] 中获取 [high]、[low] 和 [text],但我似乎无法在不导致错误或结果为空的情况下将它们取出。我在 Stackoverflow 上搜索过类似的问题,但没有一个是相同的,或者我只是不明白/不知道如何使用给出的答案。

我希望这里有人可以帮助我,因为我花了太多时间试图解决这个问题。

谢谢

【问题讨论】:

    标签: php arrays json multidimensional-array yahoo-weather-api


    【解决方案1】:

    您可以像这样访问数组索引 0 中的元素:

    echo $weather[0]['high'];     //output: 62
    echo $weather[0]['low'];      //output: 48
    echo $weather[0]['text'];     //output: Rain
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-09
      • 2017-07-09
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      相关资源
      最近更新 更多