Reputation: 85
I am trying to have a menu where the parent category can have as many child categories. The child categories can have as many sub child categories and so on......
Eg:
any insight for this ???
PS. Using Codeigniter HMVC
Currently I am working by :
Using a helper function...
I can view 2 level nested categories by the following code:
<ul>
<?php foreach($results as $row){ ?>
<li>
<?php echo $row->cat_title; ?>
<?php
$childs = get_child_cat_by_id($row->cat_id);
if(!empty($childs)){ ?>
<ul>
<?php
foreach($childs as $child){ ?>
<li><?php echo $child->cat_title; ?>
<?php
$sub_child = get_sub_childs($child->cat_id);
if(!empty($sub_child)){ ?>
<ul>
<?php
foreach($sub_child as $children){ ?>
<li><?php echo $children->cat_title; ?> </li>
<?php }?>
</ul>
<?php } ?>
</li>
<?php }?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
this code is used in the view. i need a recursive method so that the function get_child_cat_by_id need not be called many times.
Upvotes: 1
Views: 1875
Reputation: 364
The best solution I have for your problem would be to use an ORM supproting hierarchical data like Doctrine 2 or Rapid Data Mapper with the nested set extention
But a simpler solution would be to get a nested array of your data (deal with your model for that) and try something like:
//Make a list from an array
function nestedArrayToList($array, $property)
{
$output = '<ul>';
foreach ($array as $key => $mixedValue) {
if (is_array($mixedValue)) {
// Recursive step
$output .= '<li>' . nestedArrayToList($mixedValue) . '</li>';
} else {
// Simply output the property
$output .= '<li>' . $mixedValue->$property . '</li>';
}
}
$output .= '</ul>';
return $output;
}
nestedArrayToList($row)
I did not tested it, but the idea is here.
Upvotes: 1