2018-03-22 15:26
浏览 285


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>';


图片转代码服务由CSDN问答提供 功能建议

我试图循环遍历从json文件解码的PHP数组。 我得到了结果但它只给了我文件中数组的第一个结果。 我怎么能让它循环? 这是我的代码:

  foreach($ events as $ event){
 echo $ event ['d'] ['Tree1'] [0] ['  Tree2'] ['Field1']。  '&lt; br&gt;'; 
 echo $ event ['d'] ['Tree1'] [0] ['Tree2'] ['Field2']。  '&lt; br&gt;'; 
 echo $ event ['d'] ['Tree1'] [0] ['Tree2'] ['Field3']。  '&lt; br&gt;'; 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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:

    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.

    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!

    解决 无用
    打赏 举报

相关推荐 更多相似问题