I'm working with a method that builds navigation for my site through recursion and I'm having trouble adding style. The way my method is built I can't seem to figure out a way to make the parent a parent class and the child a child class so in CSS I can style the two. In case it will make things easier to understand here is an example of my database:
Here's an example of the output I'm trying to achieve:
<ul>
<li class="parent">Parent
<ul>
<li class="child">Child 1</li>
<li class="child">Child 2</li>
<li class="child">Child 3</li>
<li class="child">Child 4</li>
</ul>
</li>
</ul>
The current code puts child in every instance of <li>
. I've tried many different things and this is killing me. Here's the code:
/* i'm using pdo to pull all the categories out of MySQL, NULL means it will be a parent category */
$array = $categoryVIEW->fetchAll(PDO::FETCH_ASSOC);
$this->buildSide($array,NULL)
private function buildSide($items,$parent)
{
$hasChildren = false;
$outputHtml = '<ul>%s</ul>';
$childrenHtml = '';
foreach($items as $item)
{
if ($item['parent'] == $parent)
{
$hasChildren = true;
$childrenHtml .= '<li><a href="?c='.$item['category_id'].'">'.$item['category_name'];
$childrenHtml .= $this->buildSide($items,$item['category_id']);
$childrenHtml .= '</a></li>';
}
}
if (!$hasChildren)
{
$outputHtml = '';
}
return sprintf($outputHtml,$childrenHtml);
}
I'm sure it's something easy, but I'm stuck :(
Thanks for having a look!
UPDATE
I've been playing around with my code and added a conditional to check for the $parent
being NULL
and if so make $class
a parent, otherwise make $class
child. The problem I'm having is I'm getting an unwanted <ul></ul>
after every child? What's weird is when I change $child = false;
it eliminates my erroneous <ul></ul>
, but makes everything parent.
private function buildSide($array,$parent)
{
$child = ($parent === NULL)?false:true;
$html = '';
$tag = '<ul>%s</ul>';
$class = ($child)?'child':'parent';
foreach($array as $item)
{
if($item['parent'] === $parent)
{
$child = true;
$html .= '<li class="'.$class.'">'.$item['category_name'];
$html .= $this->buildSide($array,$item['category_id']);
$html .= "</li>\n";
}
}
if(!$child)
{
$tag = '';
}
return sprintf($tag,$html);
}