Tree generator for multi dimensional arrays

If you have a multideminsional array and would like to generate a

    like this:
  • 30
    • 31
      • 40
      • 33
      • 36
        • 41
    • 32
      • 38
    • 34
      • 37
      • 35
  • 39

Try my class out for size:

class Tree
{
    private $data;
    private $html;
    
    public function buildTree(array $data, $parent_id)
    {
        $this->data = $data;
        $this->html = '<ul>';
        $this->getChildren($parent_id);
        $this->html .= '</ul>';
        return $this->html;
    }
    
    private function getChildren($parentId)
    {
        $children = array();
        foreach ($this->data as $row) {
            if ($row['parentid'] == $parentId) {
                $children[] = $row;
            }
        }
        foreach($children as $child)
        { 
            $this->html .= '<li>'.$child['name'].'<ul>';
            $this->getChildren($child['id']); 
            $this->html .= '</ul></li>';
        } 
    
    }
}
    

$tree = new Tree();
$ul = $tree->buildTree($data, 0);
echo $ul;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s