如何在PHP中解析ElasticSearch JSON [英] How to parse ElasticSearch JSON in PHP
问题描述
我之前解析基本的JSON文件没有问题,但是这个文件的结构(来自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"
}
}
]
}
}
现在,假设我要获得两个结果结果的'title'值.我尝试了很多不同的尝试,但都没有成功.例如:
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.
推荐答案
正如Marc B所说,var_dump($ myobj)将为您提供json对象的结构.
要遍历对象的属性,请使用以下代码:
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;
}
}
这篇关于如何在PHP中解析ElasticSearch JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!