Parent Child Tree Function

This tutorial will help you to create the parent child tree concept using capplication component in yii framework.

I have added the source code to create this format array. Database containing following fields.
categoryid|categoryname|parentid


<?php
class Datacomponent extends CApplicationComponent
{
    public $allchild;

    public function init()
    {
    }
	
    // GET CATEGORY LIST
    public function getCategorylist()
    {
        $categorymodel=Category::model()->findAll(array(
                'select'=>'categoryname,parentid,categoryid'
            ));        
        return $categorymodel;                                  
    } 

    // PARENT FUNCTION OF PARENT CHILD TREE CONCEPT   
    public function parentchildlist($categoryid)
    {
        // GET CATEGORY
        $categorylist = Yii::app()->Datacomponent->getCategorylist();
        $listdata='';
        $this->allchild='';
        foreach($categorylist as $row)
        {
            if($row['parentid']==''){
                $parentlist[]=$row['categoryid'];
            }
            else{
                $listdata[$row['parentid']][]=$row['categoryid'];            
            }   
            $listdata['categoryname'][$row['categoryid']]=$row['categoryname'];        
        }
        // CALL MAKE TREE FUNCTION
        $this->maketree($listdata,$categoryid);
        return $this->allchild;
    }
	
    // MAKE TREE FUNCTION TO CREATE TREE
    function maketree($parentlist,$parentid)
    {       
        if(is_array($parentlist[$parentid]))
        {
            $this->allchild[]=$parentid;
            foreach($parentlist[$parentid] as $data)
            {
                $this->maketree($parentlist,$data);
            }
        }else {
            $this->allchild[]=$parentid;
        }    
    }      
}
?>