I have a situation where I have an array structure that consists of about 6,000 key/value pairs.
The array is in a structure like:
Array
(
[0] => Array
(
[parent] => parentA
[name] => child1
)
[1] => Array
(
[parent] => parentB
[name] => childC
)
[2] => Array
(
[parent] => parentA
[name] => child2
)
[3] => Array
(
[parent] => parentC
[name] => child3
)
[4] => Array
(
[parent] => child1
[name] => child4
)
[5] => Array
(
[parent] => child4
[name] => child5
)
From that data source I am trying to massage the output into
A) An array that I can use in later functionality
B) A table display where each row will be one full chain, and each column will be a level deeper. Essentially if you think of page navigation, this is a bread crumb display where each node would be in the next column.
I have been playing with a few approaches here
1) Using the recursive function at this stack overflow question: https://stackoverflow.com/a/2915920/997226, however I have not been able to modify this to work with my data where the parent can be the same. In their example of $tree, the left hand (key) value is always unique.
I understand in their example their key is the child, and the value (right hand side) is the parent, however I still can not get this to work for me as in my data there are multiples of the same item on both the parent side and the child side. (Think complex relationships where an article can be contained within multiple parent categories.
2) I have tried starting to create a "base array" of unique parent elements, and then creating a recursive function to do a search on the "original key value array" but this didn't quite work either.
3) I tried saving the data in a database as I'm pretty familiar with using left/right values for accessing/manipulating data as a nested set, but I'm trying to avoid having to have everything INSERT/SELECT from a database.
4) I tried working with the various PHP Iterators classes as I have used these successfully for working with the file system and building file/directory listings, so I've been playing with RecursiveArrayIterator / ParentIterator/ArrayIterator, but can't seem to figure out the proper syntax to use.
I understand that recursing may not be as efficient as using references for a data set of this size, however it seems like it provides the most flexibility, I just can't seem to get it to iterate recursively correctly.
Beyond, this specific question, I'm also trying to better understand the algorithm nature of programmatic recursion.
The more I read through other people's code examples that are trying to do something similar, but with a different data structure I just become more confused.
If anyone could help point me in the right direction it would be appreciated.
Clarification Notes
- There will be multiple levels.
- It has been pointed out that the data structure can be thought of as a Directed acyclic graph and that makes complete sense.