Mic*_*elH 3 php arrays loops multidimensional-array
我有一个类似于这个的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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图循环遍历这个数组(我已经使用JSON解码将其转换为PHP),并且对于每个"Pages"块我想添加额外的数据.
例如,工作应该如下所示:
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
Run Code Online (Sandbox Code Playgroud)
每次它通过一个部分,我希望它与另一个数组合并.
我正在努力编写代码,每当它找到"Pages"这个词作为关键时,它就会继续循环.我曾尝试多次,但一直在废弃我的代码.
任何帮助都会很棒!
您正在寻找一个递归函数,将您的数组扫描到深度n.像这样的东西可以工作:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
你现在可以通过调用来使用它 findPagesInArray($json_object)