【问题标题】:How to get value from array with objects?如何从带有对象的数组中获取值?
【发布时间】:2022-01-08 15:05:16
【问题描述】:

我尝试使用 api.openweathermap.org 获取当前天气。我使用 php 请求来获取数据。我成功接收数据并将其转换为带有对象的数组。我有一个小问题:如何获得一个名为“MAIN”的键的值,它等于“Snow”? 我尝试使用 api.openweathermap.org 获取当前天气。我使用 php 请求来获取数据。我成功接收数据并将其转换为带有对象的数组。我有一个小问题:如何获取名为“MAIN”的键的值,它等于“Snow”?

object(stdClass)#3 (14) {
  ["coord"]=>
  object(stdClass)#1 (2) {
    ["lon"]=>
    float(30.2642)
    ["lat"]=>
    float(59.8944)
  }
  ["weather"]=>
  array(1) {
    [0]=>
    object(stdClass)#4 (4) {
      ["id"]=>
      int(600)
      ["main"]=>
      string(4) "Snow"
      ["description"]=>
      string(27) "small snow"
      ["icon"]=>
      string(3) "13n"
    }
  }
  ["base"]=>
  string(8) "stations"
  ["main"]=>
  object(stdClass)#5 (6) {
    ["temp"]=>
    float(-11.94)
    ["feels_like"]=>
    float(-18.94)
    ["temp_min"]=>
    float(-15.2)
    ["temp_max"]=>
    float(-11.08)
    ["pressure"]=>
    int(1010)
    ["humidity"]=>
    int(86)
  }
  ["visibility"]=>
  int(10000)
  ["wind"]=>
  object(stdClass)#6 (2) {
    ["speed"]=>
    int(4)
    ["deg"]=>
    int(100)
  }
  ["snow"]=>
  object(stdClass)#7 (1) {
    ["1h"]=>
    float(0.5)
  }
  ["clouds"]=>
  object(stdClass)#8 (1) {
    ["all"]=>
    int(100)
  }
  ["dt"]=>
  int(1641652836)
  ["sys"]=>
  object(stdClass)#9 (5) {
    ["type"]=>
    int(2)
    ["id"]=>
    int(197864)
    ["country"]=>
    string(2) "RU"
    ["sunrise"]=>
    int(1641624902)
    ["sunset"]=>
    int(1641647737)
  }
  ["timezone"]=>
  int(10800)
  ["id"]=>
  int(498817)
  ["name"]=>
  string(29) "SPb"
  ["cod"]=>
  int(200)
}

【问题讨论】:

  • 这不是一个数组,它是一个对象。我建议您看一些 PHP 入门教程,这些教程将向您展示如何获取对象的属性。

标签: php arrays object


【解决方案1】:

你可以得到这样的值:

$weatherType = $weather->weather[0]->main;

【讨论】:

    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2016-06-19
    • 2021-02-07
    相关资源
    最近更新 更多