Loop through nested arrays PHP

不羁的心 提交于 2020-12-15 06:34:56

问题


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:


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!



来源:https://stackoverflow.com/questions/49432519/loop-through-nested-arrays-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!