【问题标题】:Trying to access json array data with php尝试使用 php 访问 json 数组数据
【发布时间】:2021-08-23 21:54:31
【问题描述】:

我正在尝试将从我的 php curl 请求返回的数据量减少到仅需要的数据量,但我正在努力从内部数组/对象访问数据。

我目前收到 $weatherdata 中的索引未定义的错误。

警告:第 21 行项目名称中存在非法字符串偏移“当前”

这是返回的数据:

{
  "lat": 33.44,
  "lon": -94.04,
  "timezone": "America/Chicago",
  "timezone_offset": -21600,
  "current": {
    "dt": 1618317040,
    "sunrise": 1618282134,
    "sunset": 1618333901,
    "temp": 284.07,
    "feels_like": 282.84,
    "pressure": 1019,
    "humidity": 62,
    "dew_point": 277.08,
    "uvi": 0.89,
    "clouds": 0,
    "visibility": 10000,
    "wind_speed": 6,
    "wind_deg": 300
 }
    "daily": [
    {
      "dt": 1618308000,
      "sunrise": 1618282134,
      "sunset": 1618333901,
      "moonrise": 1618284960,
      "moonset": 1618339740,
      "moon_phase": 0.04,
      "temp": {
        "day": 279.79,
        "min": 275.09,
        "max": 284.07,
        "night": 275.09,
        "eve": 279.21,
        "morn": 278.49
      },

然后是我当前的 php 代码:

<?php


    $url='https://api.openweathermap.org/data/2.5/onecall?lat=' . $_REQUEST['lat'] . '&lon=' . $_REQUEST['lng'] . '&units=metric&appid=foo';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);
    
    $countryData = [];

    foreach($decode as $weatherdata){
        $countryinfo = [];
        $countryinfo['uv'] = $weatherdata['current']['uvi'];
        $countryinfo['todaytemp'] = $weatherdata['daily'][0]['temp']['day'];
          
        array_push($countryData, $countryinfo);
    };

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['data'] = $countryData;


    echo json_encode($output); 

?>

任何指导将不胜感激!谢谢

【问题讨论】:

  • 请给我们看一段有效/完整的 JSON
  • 请发布完整的json
  • 也分享预期的结果

标签: php arrays json curl


【解决方案1】:

您的foreach 导致此错误。您正在遍历生成的数组

当您使用json_decode($result, true) 解码上述 json 时,生成的数组会是这样的

 foreach($decode as $weatherdata){
// On first Iteration, $weatherdata will be "lat":33.44,
// On Second Iteration, $weatherdata will be "lon":-94.04,
// On Third Iteration, $weatherdata will be "timezone":"America/Chicago",
}

所以如果你尝试访问$weatherdata['current']['uvi'];你会得到未定义的索引错误

要获得 UVI,您必须致电

$uvi = $decode['current']['uvi'];

daily获取今天的温度

$todaysTemp = $decode['daily'][0]['temp']['day'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2016-10-08
    相关资源
    最近更新 更多