duanchijie2323 2014-04-16 18:38
浏览 38

如何在PHP中解析ElasticSearch JSON

I've parsed basic JSON files with no trouble before, but the structure of this one (from ElasticSearch) is completely confusing me. Here's a stripped down example of the JSON I'm working with:

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

Now, let's say I want to get the 'title' value of both results result. I have tried a lot of different things with no success. For example:

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

}

I've tried a lot of different variations, but I'm just not exactly sure how to parse this structure. Any help would be hugely appreciated.

  • 写回答

2条回答 默认 最新

  • dotibrb048760 2014-04-16 19:06
    关注

    As Marc B stated, var_dump($myobj) will give you the structure of the json object.

    To iterate over the properties of an object use this:

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

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据