0

I need to generate a array structure like a tree. I would like to achieve someone like this:

<ul>
   <li>Catalog1
    <ul> 
        <li>Subcatalog1
            <ul> 
                <li> 
                    Subsubcatalog1
                </li> 
                <li> 
                    Subsubcatalog2
                </li> 
            </ul> 
        </li> 
        <li> 
            Item2
        </li> 
        <li> 
            Item3
        </li> 
    </ul> 
</li> 
<li> 
    Catalog2
</li>
</ul>

I have data array from database which have field nadrzedny_id and podrzedny_id. And dependecy is nadrzedny_id is a parent for podrzedny_id. Root element has null in nadrzedny_id and has id = 1. Tree can't be close (it can has many branches).

Each element of array has:
$element->id
$element->level (depth)
$element->podrzedny_id
$element->nadrzedny_id
$element->nazwa (name to display)
$element->id is always equal $element->podrzedny_id.

Please help.

2
  • I tried to do this with very big array with one element as root, but i don't know how i can do with one loop, because I can't do this on concrete amount pf loops. Commented Oct 25, 2012 at 17:19
  • Kindly read this article: mattgemmell.com/2008/12/08/what-have-you-tried Commented Oct 25, 2012 at 20:42

1 Answer 1

1

Kindly read this article, I'm sure it will help you. Basic ideas:

  1. You need a class for Nodes.

  2. You need to store in the nodes their ids, types (ul or li) and nazwa.

  3. There are two types of algorithms for traversing a tree: Depth-first and Width-first. You can find thousands of articles describing those algorithms with a quick search. Also, you have an option to use already created tools for trees.

  4. When you add a node, you know its parent's id, so you have to traverse the tree until you find the node's parent.

  5. When you have finished creating the tree, it's very easy to create the output string, by using depth-first tree traversing and paying attention to close your tags in the place appropriate for closing your tag.

  6. Finally you write your result somewhere (where you need the result).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.