douzhang5984 2019-02-27 19:27
浏览 72

PHP - 循环遍历数组中的消息

I have weird problem with my PHP code. I decoded an elasticsearch json, and I got this array:

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. ) ) ) ) ) )

What I want is only to print the "messages".

If I run this code:

$echo json_decoded['hits']['hits']['0']['_source']['message']['0']

It echo "2019-02-25T13:57:40+0000 ERROR something happened in this execution."

And if I run this code:

$echo json_decoded['hits']['hits']['1']['_source']['message']['0']

It echo "2019-02-25T14:00:13+0000 INFO takes the value and converts it to string."

ALL GOOD SO FAR, but now I want to run it as loop, to print the messages. I made the following loop:

foreach($json_decoded['hits']['hits'] as $host) {
    echo $host[$index]['_source']['message']['0'];
    $index++;
}   

I don't get any output. What is the problem?

  • 写回答

1条回答 默认 最新

  • dqrfdl5708 2019-02-27 19:38
    关注

    When you foreach over ['hits']['hits'] this will iterate over the next level of the array (so the ['0'] and ['1'] elements). So you don't need to add in the [$index] part of your echo or the $index value...

    foreach($json_decoded['hits']['hits'] as $host) {
        echo $host['_source']['message']['0'];
    }   
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本