I need to create a tree menu of "nth" subcategories. I settled on using the adjacency list model for my table structure, because I won't be updating this table very much and this seemed the easiest to implement for my use.
I want to style the output using "ul" and "li" tags...I already have a css and jquery solution to do the styling. My problem comes from pulling the data out of the database and using a recursive function via PHP to build the list ... the list is a concatenated string that gets parsed to build the tree. I'm really having a hard time getting the closing "ul" and "li" tags to line up just where they need to be.
Is this the best way to do this? Are there other better ways using arrays or something like that to do this? Any examples you can point me to of "best practices" for building a list like this will be appreciated. Thanks.
Here's my table structure:
portfolio_id (int), p_name (varchar), parent_portfolio_id (int) Here's what I want the data to look like when presented:
<ul>
<li>Portfolio Name
<ul>
<li>Sub portfolio A
<ul>
<li>Sub portfolio A - 1</li>
<li>Sub portfolio A - 2</li>
<li>Sub portfolio A - 3</li>
</ul>
</li>
<li>Sub portfolio B</li>
<li>Sub portfolio C</li>
</ul>
</li>
</ul>
Here's the current recursive function:
function portf($ndb, $portfolio_id, $space=1, $x="", $level=1) // cat id, space to add "_" degree of categoreis times, list of categories
{
$sql = "SELECT portfolio_id, p_name, parent_portfolio_id FROM portfolio WHERE parent_portfolio_id = $portfolio_id ORDER BY p_name ASC;";
$select = $ndb->get_results($sql, 0, ARRAY_A);
if( !is_null($select) )
{
foreach($select as $data)
{
$x = $x . $data->portfolio_id . '_' . $data->parent_portfolio_id . '_' . $level . str_repeat('_', $space) . $data->p_name . '-';
$x = $this->portf($ndb, $data->portfolio_id, ($space+1), $x, ($level+1) );
}
return $x;
}
else
{
return $x;
}
}