遍历嵌套数组PHP [英] Loop through nested arrays PHP

查看:68
本文介绍了遍历嵌套数组PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历从json文件解码的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>';

}

推荐答案

听起来像是您试图遍历.您可以通过循环遍历数组来正确开始,但是随后就会陷入困境,因为循环中的每个元素都是...另一个数组.因此,要回显子数组的值,您想在循环内部运行第二个循环.本质上,如果您的循环命中了一个子数组,那么您也要遍历该数组.如果您知道您的数组仅由子数组组成,则可以这样做:

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

php手册中也有一些示例.如果只需要来自特定键的数据,则还可以添加条件语句.祝你好运!

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!

这篇关于遍历嵌套数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆