3

我有一个类似于此的 JSON 文件:

{
"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 解码将其转换为 PHP),并且对于每个“页面”块,我都想添加额外的数据。

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

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

每次它通过一个部分时,我希望它与另一个数组合并。

我正在努力编写代码以查看它每次找到“Pages”这个词作为键时都在循环。我尝试了很多次,但一直在报废我的代码。

对此的任何帮助都会很棒!

4

1 回答 1

5

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)

于 2013-04-10T04:41:06.307 回答