从 JSON 文件中获取第一个对象

Getting first object from a JSON file

如果我不知道 "pageid",如何访问 "thumburl"?

{
  "continue": {
    "iistart": "2004-12-19T12:37:26Z",
    "continue": "||"
  },
  "query": {
    "pages": {
      "30260": {
        "pageid": 30260,
        "ns": 6,
        "title": "File:Japanese diet inside.jpg",
        "imagerepository": "local",
        "imageinfo": [
          {
            "thumburl": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Japanese_diet_inside.jpg/130px-Japanese_diet_inside.jpg",
            "thumbwidth": 130,
            "thumbheight": 95,
            "url": "https://upload.wikimedia.org/wikipedia/commons/e/e1/Japanese_diet_inside.jpg",
            "descriptionurl": "https://commons.wikimedia.org/wiki/File:Japanese_diet_inside.jpg",
            "descriptionshorturl": "https://commons.wikimedia.org/w/index.php?curid=30260"
          }
        ]
      }
    }
  }
}

在 php 中有多个对象我可以这样做 imageinfo[0] 但是如果我把 $imageurl = $data->query->pages[0]->imageinfo[0]->thumburl; 它不起作用因为它是一个对象而不是数组。

我该怎么做?

你可以遍历它,所以你不需要像这样的数组键:

$pages = (array) $data->query->pages;
foreach($pages as $page) {
  $imageinfo = $page->imageinfo[0]->thumburl;
}

但这只会让您在页面列表中排在最后。因此,如果您知道有更多页面,则需要将这些 thumburl 存储在数组中。或者如果你确定你只想要第一个,那么在第一个循环之后 exit

您可以调用 get_object_vars 获取对象属性的关联数组,然后获取其中的第一个。

$props = array_values(get_object_vars($data->query->pages));
$imageurl = $props[0]->imageinfo[0]->thumburl;

您可以使用 reset() 获取第一个元素:

$data = json_decode($json) ;
$elem = reset($data->query->pages) ;
$imageurl = $elem->imageinfo[0]->thumburl ;

另一种方法是解码为数组,re-index 所以它总是从 0:

开始
$result = array_values(json_decode($json, true)['query']['pages'])[0];

然后你就可以访问$result['imageinfo']['thumburl']或者把它附加到上面。