I have this array:
Array
(
[1] => animal
[1-1] => turtle
[1-1-1] => sea turtle
[1-1-2] => box turtle
[1-1-3] => green turtle
[1-1-3-1] => green turtle with brown tail
)
and I want some how to convert it into:
Array
(
[1-title] => animal
[1-sons] => array(
[1-1-title] => turtle
[1-1-sons] => array(
[1-1-1] => sea turtle
[1-1-2] => box turtle
[1-1-3-title] => green turtle
[1-1-3-sons] => array(
[1-1-3-title] => green turtle
)
)
)
)
or maybe you can suggest a better way for organizing the outputted array..
but how to do that?
I know that's not easy task at all, I'm writing a parser that will walk on data and make tree out of them..
Thanks in advance for your help and advices..
Best Solution
The easiest way of organizing your data would be in such a way:
Essentially, the name of the animal is the value, unless it has children, then the value is an array and the key is the animal name.
That way, you can easily parse the values by doing the following:
The above in the console will output the following:
EDIT: And here is a version that will output it for a webpage.
The output is:
Maybe you want to get the children of an animal.
Now we can get all the children of the
Green Turtle
and output them.The output is:
EDIT: Since you say you are stuck with the input array being in that weird format, here is a function that will convert your array into the format I specified above: