dpl3350 2013-04-10 04:36
浏览 57
已采纳

循环通过多维数组

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

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.

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!

  • 写回答

1条回答 默认 最新

  • dtx9763 2013-04-10 04:41
    关注

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

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

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站