Hello Reader's if your making the parent child relationship then this blog is very helpful to you. Here we are making parent child tree by using the Iteration functions. The output of this will a tree which showing the childs on branches and parents on the nodes.
Consider the database first. The database will having the 3 column ie id, parent_id and category_name. Here id will be unique for every category and subcategory, parent_id will be 0 for all parent category and if there is childs(Sub categories in this) this will be id of that parent, last the category_name will be the name of category or subcategory.
As you hit the mysql query you will be getting the seperated column record. Now we start the logic
First we create function for creating the tree first.
public function buildTree($items)
{
$childs = array();
foreach($items as $item)
$childs[$item->parent_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
return $childs[0];
}
Now we create another function that will Llst all the parent and child categories in a tree structure with appropriate links. This is iterative function, if any child found having child in it. The will again traverse to it by calling the same function again. And it's code will go like this:-
public function traverseChild($childs)
{
foreach ($childs as $key => $child) {
$ctemp = array();
$ctemp['id'] = $child['id'];
$ctemp['text'] = $child['category_name'].'<span class="actions"><span class="actions"><a title="Click to add/update attributes abd category updates" href="'.base_url().'admincategories/assembleCategory/'.$child['id'].'">Assemble Category</a></span></span>';
if (!empty($child['childs'])) {
$childrenArray = $this->traverseChild($child['childs']);
$ctemp['children'] = $childrenArray;
}
$categoryChild[] = $ctemp;
}
return $categoryChild;
}
The above function will give you the result of all child. Now you can easily put them in views and by calling some css and js you can give it look like a tree. Output will as in screenshot below:-
![](http://findnerd.s3.amazonaws.com/imagedata/4112/4112.png)
0 Comment(s)