I am (via a web service) receiving a flat XML file that contains a listing of categories, subcategories, subsubcategories, etc, all at the same level. (i.e. Subcategories are not nested under their parent categories.) This, unfortunately, cannot be changed. I have to work with the data provided.
I'm taking this XML and converting it into an object, then into an array using simplexml_load_string and array_map. This is all working as expected. What I'm left with is a master category array that looks something like this.
Array
(
[0] => Array
(
[CategoryID] => HARDWARE
[Description] => Hardware Issue
)
[1] => Array
(
[CategoryID] => MAC_OSX
[Description] => Mac OSX
[ParentCategoryID] => OS
)
[2] => Array
(
[CategoryID] => OFFICE
[Description] => Microsoft Office
[ParentCategoryID] => SOFTWARE
)
[3] => Array
(
[CategoryID] => OS
[Description] => Operating Systems
[ParentCategoryID] => SOFTWARE
)
[4] => Array
(
[CategoryID] => WIN_7
[Description] => Windows 7
[ParentCategoryID] => OS
)
[5] => Array
(
[CategoryID] => SOFTWARE
[Description] => Software Issue
)
)
As you can see, there are subcategories mixed in there, all keyed off of the ParentCategoryID. Parent Categories have that field omitted.
The CategoryID will always be unique, no matter what level it is on. And the array is sorted alphabetically by the Description. The real array is over 250 categories long, above is an abbreviated version for example sake.
I need to take that master array, loop through it and come up with a new array that looks something like this.
Array
(
[0] => Array
(
[CategoryID] => SOFTWARE
[Description] => Software Issue
[SubCategories] => Array
(
[0] => Array
(
[CategoryID] => OS
[Description] => Operating Systems
[SubCategories] => Array
(
[0] => Array
(
[CategoryID] => WIN_7
[Description] => Windows 7
)
[1] => Array
(
[CategoryID] => MAC_OSX
[Description] => Mac OSX
)
)
)
[1] => Array
(
[CategoryID] => OFFICE
[Description] => Microsoft Office
)
)
)
[1] => Array
(
[CategoryID] => HARDWARE
[Description] => Hardware Issue
)
)
Things I have to keep in mind is there may be infinitely many subcategories (so there isn't a set number of sublevels I can hard-code in). I've been trying to mess around with array_search and array_filter, but I'm just not having any luck getting something working. I obviously don't want to loop hundreds of times for this process to happen.
Does anyone with a little more experience with multidimensional arrays under their belt have some ideas, direction, or an example that may help me achieve my desired result?
Description. The array above was hand-crafted here as an example; The real array has over 250 categories.CategoryIDwill always be unique, no matter what level it is on. The XML is flat as well.