2

I have category table:

CategoryID    CategoryName   ParentID
     1           Root          Null
     2           News            1
     3           Horoscope       1
     4           Sports          2
     5           National        2
     6           Daily           3
     7           Aries           6
     8           Weekly          3
     9           Aries           8

I am trying to create the tree structured json data as follows:

[{
    "id":1,
    "text":"Root",
    "children":[{
        "id":2,
        "text":"News",
        "state":"closed",
        "children":[{
            "id":4,
            "text":"Sports"
        },{
            "id":5,
            "text":"National"
        }]
    },{
        "id":3,
        "text":"Horoscope",
        "children":[{
            "id":6,
            "text":"Daily",
                        "children":[{
                  "id":7,
                  "text":"Aries"
                  }],

         },{
            "id":8,
            "text":"Weekly",
                        "children":[{
                  "id":9,
                  "text":"Aries"
                  }],
            }
        }]
}]

I have following function to render all category and sub category

   public function categoryData($parent)
    {                 
        $model=new Category();
        $cat=$model->findAllByAttributes(array('ParentCategoryID'=>$parent,'Status'=>2));

        $category = array();


        foreach($cat as $record) 
        {
          global $category;
          $category['id'][$record->CategoryID] = $record->CategoryID;
          $category['text'][$record->CategoryID] = $record->CategoryName;


          // $category['children'][$record->CategoryID] = array();

          //$names[] = $record->CategoryName;

          $this->categoryData($record->CategoryID);

        }
        //array_push($category['children'][$record->ParentCategoryID], $category['children'][$record->CategoryID]);
        return $category;
    }

Problem: but above action doesn't place category in array in proper format so that I can create the above json data format by applying json_encode($category) function.

How to place the category data using recursion function in tree structured array?

CodeManiac
  • 974
  • 8
  • 34
  • 56
  • You want to look at this question http://stackoverflow.com/questions/4196157/create-array-tree-from-array-list – antony Apr 20 '13 at 13:55

1 Answers1

1

Add a public $children = array() property to your Category model. Then loop over the result and set a reference in the parent's $children array:

$categories = Category::model()->findAll(array('index'=>'id'));
foreach($categories as $category)
    $categories[ $category->id_parent ]->children[] = $category;

echo json_encode($categories);
Michael Härtl
  • 8,428
  • 5
  • 35
  • 62