【问题标题】:How to parse ElasticSearch JSON in PHP如何在 PHP 中解析 ElasticSearch JSON
【发布时间】:2014-05-31 19:19:29
【问题描述】:

我之前已经毫无问题地解析了基本的 JSON 文件,但是这个(来自 ElasticSearch)的结构完全让我感到困惑。这是我正在使用的 JSON 的精简示例:

{
  "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"
        }
      }
    ]
  }
}

现在,假设我想获取两个结果结果的“标题”值。我尝试了很多不同的事情,但都没有成功。例如:

//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;

}

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

【问题讨论】:

  • var_dump($myobj) 会告诉你确切的结构。
  • 谢谢你,这让我走上了正轨。

标签: php json elasticsearch


【解决方案1】:

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

要迭代对象的属性,请使用以下命令:

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

【讨论】:

    【解决方案2】:

    我明白了。以下代码供以后可能会发现它有用的任何人使用:

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

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2019-05-18
      • 2021-11-23
      • 2016-10-08
      • 2013-04-06
      • 2014-04-16
      • 2014-04-07
      • 1970-01-01
      • 2012-01-21
      相关资源
      最近更新 更多