通过一个多维数组循环 [英] Looping through a multi-dimensional array

查看:160
本文介绍了通过一个多维数组循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件,类似于这样:

I have a JSON file that looks similar to this:

{
"Pages":{
        "/":{
            "Name": "Home",
            "Page": "index.php"
        },

        "/_admin":{
            "Name": "Admin",
            "Page": "_admin/index.php",

            "Template": "admin",
            "MobileTemplate": "admin-mobile",

            "Pages":{

                "/settings":{
                    "Name": "Settings",
                    "Page": "_admin/settings/index.php",
                    "Config": "_admin/settings/config.php",

                    "Pages":{

                        "/user":{
                            "Name": "Users",
                            "Page": "_admin/settings/user.php",
                            "Config": "_admin/settings/config.php",
                            "CatchAll": true
                        }

                    }

                }
            }
        },

        "/tasdf":{
            "Name": "fs",
            "Page": "index.php"
        }
    }
}

我在这个数组试图循环(我使用JSON德code把它变成PHP),并为页面我要添加额外的数据每个块。

I am trying to loop through this array (I have used JSON decode to turn it into PHP), and for every block of "Pages" I want to add extra data.

例如,工作应该是这样的:

For example, the working should look like this:

Array Loop Starts
Finds "Pages"
    -Goes through "/"
    -No "Pages" - continue
   - Goees through "/_admin"
       -Finds "Pages"
       -Goes through "/settings"
           -Finds "Pages"
           -Goes Through "/user"
           -No Pages Continue
   - Goes through "/tasdf"
   - No "Pages" - continue
 End Loop

每次它经历的一部分,我希望它与另一个阵列合并。

Everytime it goes through a part, I want it to merge with another array.

我奋力写作code看到它不断循环,每次它找到的单词页为重点。我曾尝试很多次,但保持再杀我的code。

I am struggling writing code to see it keep looping everytime it finds the word "Pages" as the key. I have attempted many times but keep scrapping my code.

任何帮助,这将是巨大的!

Any help with this would be great!

推荐答案

您正在寻找的扫描阵列以的深度递归函数n 。像这样的东西可以工作:

You're looking for a recursive function that scans your array to a depth of n. Something like this could work:

function findPagesInArray($myArray) {
    foreach($myArray as $index => $element) {
        // If this is an array, search deeper
        if(gettype($element) == 'array') {
            findPagesInArray($element);
        }

        // Reached the Pages..
        if($index == 'Pages') {
            // Do your task here
        }
    }
}

和你现在会通过调用使用 findPagesInArray($ JSON_OBJECT)

And you would now use it by calling findPagesInArray($json_object)

这篇关于通过一个多维数组循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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