dpt1712 2018-03-22 15:26
浏览 320
已采纳

循环遍历嵌套数组PHP

Im trying to loop through PHP arrays decoded from a json file. I get the results but it only gives me the first results of the arrays in the the file. How can I make it loop? This is my code:

foreach ($events as $event) {

  echo $event['d']['Tree1'][0]['Tree2']['Field1'] . '<br>';
  echo $event['d']['Tree1'][0]['Tree2']['Field2'] . '<br>';
  echo $event['d']['Tree1'][0]['Tree2']['Field3'] . '<br>';

}
  • 写回答

1条回答 默认 最新

  • duanchi19820419 2018-03-22 16:27
    关注

    Sounds like you're trying to loop through the values of a "multidimensional array". You're starting correctly by going through your array with a loop, but then you're stuck because each element in your loop is... another array. So, to echo out the values of the child array, you want to run a second loop inside of your loop. Essentially, if your loop hits a child array, you want to loop through that array too. If you know your array is made of child arrays only, you can do this like so:

    <?php
    foreach ($events as $event) {
    
        foreach($event as $ev) {
    
            echo $ev;
        }
    }
    

    If you need the keys, that adds a slight layer of complexity, but nothing you can't manage.

    <?php
    foreach ($events as $event) {
        foreach ($event as $k=>$v) {
            echo $k .': '. $v; 
        }
    }
    

    There are some examples in the php manual as well. You can also add in conditionals if you only need data from specific keys. Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序