简体   繁体   中英

create json data for tree structure data with php array using recursion function

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM