I’m building a category manager via database. The following PHP generates the code I’ll paste below that:
function generate_menu($parent, $menu_array, $result = NULL)
{
$has_childs = FALSE;
foreach($menu_array as $key => $value):
if ($value['parent'] == $parent):
$result .= '<li id="list_'.$value['id'].'" class="item">';
$result .= '<div class="item">' . $value['name'] . '</div>';
if ($has_childs):
$has_childs = FALSE;
$result .= '<ol>';
else:
$has_childs = TRUE;
$result .= '</li>';
endif;
$result .= $this->generate_menu($key, $menu_array);
endif;
endforeach;
return $result;
}
And here’s the HTML it generates:
<li id="list_11" class="item">
<div class="item">Real Estate</div>
</li>
<li id="list_12" class="item">
<div class="item">Home Improvements</div>
<ol>
<li id="list_13" class="item">
<div class="item">Interior</div>
</li>
<li id="list_14" class="item">
<div class="item">Exterior</div>
<ol>
<li id="list_15" class="item">
<div class="item">Exterior Subcat</div>
</li>
So I’m able to close the <li> tag when it’s a parent, but if it’s an item with a parent, an <ol> enters the equation. That’s when I don’t know how to close them. I’m not sure where to put the </li> and </ol>. Everything I’ve tried just doesn’t work.
Here’s how it should look:
<li id="list_11" class="item">
<div class="item">Real Estate</div>
</li>
<li id="list_12" class="item">
<div class="item">Home Improvements</div>
<ol>
<li id="list_13" class="item">
<div class="item">Interior</div>
</li>
<li id="list_14" class="item">
<div class="item">Exterior</div>
<ol>
<li id="list_15" class="item">
<div class="item">Exterior Subcat</div>
</li>
</ol>
</li>
</ol>
</li>
EDIT:
Here is the code for passing the array and generating the menu:
$query = $this->db->get('categories');
foreach($query->result_array() as $row):
$menu_array[$row['id']] = array('name' => $row['name'], 'parent' => $row['parent'], 'id' => $row['id']);
endforeach;
echo '<ol class="sortable">';
echo $this->tasks->generate_menu(0, $menu_array);
echo '</ol>';
And here’s the print_r of $menu_array:
Array
(
[11] => Array
(
[name] => Real Estate
[parent] =>
[id] => 11
)
[12] => Array
(
[name] => Home Improvements
[parent] =>
[id] => 12
)
[13] => Array
(
[name] => Interior
[parent] => 12
[id] => 13
)
[14] => Array
(
[name] => Exterior
[parent] => 12
[id] => 14
)
[15] => Array
(
[name] => Exterior Subcat
[parent] =>
[id] => 15
)
)
I have figured this one out. I was complicating things a bit.