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!
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)