我的PHP代码有奇怪的问题。我解码了elasticsearch json,得到了这个数组:
Array ( [took] => 1 [timed_out] => [_shards] => Array ( [total] => 6 [successful] => 6 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => 7336 [max_score] => 0.8790647 [hits] => Array ( [0] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 5T8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [@version] => 1 [log-level] => ERROR [port] => 50906 [host] => 6b14cd1f183d.mynetwork [@timestamp] => 2019-02-25T14:20:01.367Z [Timestamp] => 2019-02-25T13:57:40+0000 [message] => Array ( [0] => 2019-02-25T13:57:40+0000 ERROR something happened in this execution. [1] => something happened in this execution. ) ) ) [1] => Array ( [_index] => logstash-2019.02.25 [_type] => doc [_id] => 7z8GJWkBAZbF3w3t4NF2 [_score] => 0.8790647 [_source] => Array ( [@version] => 1 [log-level] => INFO [port] => 50906 [host] => 6b14cd1f183d.mynetwork [@timestamp] => 2019-02-25T14:20:01.369Z [Timestamp] => 2019-02-25T14:00:13+0000 [message] => Array ( [0] => 2019-02-25T14:00:13+0000 INFO takes the value and converts it to string. [1] => takes the value and converts it to string. ) ) ) ) ) )
我想要的只是打印“消息”。
如果我运行以下代码:
$echo json_decoded['hits']['hits']['0']['_source']['message']['0']
它回显"2019-02-25T13:57:40+0000 ERROR something happened in this execution."
如果我运行这段代码:
$echo json_decoded['hits']['hits']['1']['_source']['message']['0']
它回显"2019-02-25T14:00:13+0000 INFO takes the value and converts it to string."
一切都很好,但现在我想将其作为循环运行,以打印消息。我做了以下循环:
foreach($json_decoded['hits']['hits'] as $host) {
echo $host[$index]['_source']['message']['0'];
$index++;
}
我没有任何输出。有什么问题吗?
答案 0 :(得分:0)
当您遍历['hits']['hits']
时,它将遍历数组的下一级(因此['0']
和['1']
元素)。因此,您无需添加[$index]
的{{1}}部分或echo
值...
$index