I have a tree-like object structure that consists of two types of objects:
CategoryCategoryLinkThe structure is the following:
The whole story begins with an array of Categories that have no parent
Each Category has a few unimportant properties and a few important:
$parent - containing an id of a parent Category,
$children - containin an array of childern Categories (may be empty if the category has no childern of course).
$links - containing an array of CategoryLinks (also possibly empty)
While __constructing a Category, I look for existing child Categories and CategoryLinks, and if there are some, I create their instances and add them to $children and $links, so this procedure repeats for the children and their children and so on, until a category with no children is reached.
So what this procedure does is that it basically creates a tree of Categories and their Links. This goes well enough, until I want to output this tree structure (using Smarty), and I'm not quite sure how to iterate over it the proper way. Desired output is something like this
Parent1 -its unimportant properties
-Child1 - its unimportant properties
-Child2 -...
-Child2's Child1
-Child2's Child2
-Child3
Parent2
-Child1
-Child1's Child1
-Child2
Parent3
...
I'm not sure if its better to iterate over it in PHP and convert it to a multi-dimensional array and iterate over it in Smarty, or do it all the way in Smarty.
*note that I didn't mention objects of class CategoryLink, as the Category may contain only one-dimensional array of them, so iterating over them is rather easy, I'm just not sure how to iterate over the whole structure.
What is the best | right way to do this?
Trees lend themselves to very elegant recursive operations. In this case you're describing a depth-first pre-order traversal. The Wikipedia page might be useful. As for the rest, pushing it into a multi-dimensional array sounds sensible enough if that's the easiest way for you to display it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With