如何在PHP中解析ElasticSearch JSON



我以前解析过基本的JSON文件,没有遇到任何问题,但这个文件的结构(来自ElasticSearch)让我完全困惑

{
  "took": 7,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  },
  "hits": {
    "total": 1017,
    "max_score": 2.8167849,
    "hits": [
      {
        "_index": "myindex",
        "_type": "mytype",
        "_id": "119479",
        "_score": 2.8167849,
        "_source": {
          "title": "my title",
          "url": "my url",
          "company": "my company",
          "location": "my location",
          "description": "my description",
          "industry": "my industry"
        }
      },
      {
        "_index": "myindex",
        "_type": "mytype",
        "_id": "119480",
        "_score": 2.8167849,
        "_source": {
          "title": "my title",
          "url": "my url",
          "company": "my company",
          "location": "my location",
          "description": "my description",
          "industry": "my industry"
        }
      }
    ]
  }
}

现在,假设我想得到两个结果结果的"title"值。我尝试了很多不同的事情,但都没有成功。例如:

//json_decode works fine. I have verified with a var_dump();
$myobj = json_decode($json);
//this is where I'm not sure what to do:
foreach($myobj->hits->hits->_source as $result) {
    echo $result->title;
}

我尝试了很多不同的变体,但我只是不确定如何解析这个结构。任何帮助都将不胜感激。

正如Marc B所说,var_dump($myobj)将为您提供json对象的结构

要迭代对象的属性,请使用以下方法:

foreach($myobj->hits->hits->_source as $key => $val) {
    if($key == 'title') {
        echo $val;
    }
}

我得到了。下面是稍后可能会发现它有帮助的人的代码:

foreach ($myobj->hits->hits as $result) {
echo $result->_source->title;
}

最新更新