How to show subcategories of a selected main category?
<p>I'm trying to build a navigation that when the user selects a category then the navigation will only show sub categories for that category selected. </p>

<p>I'm getting a variable from the URL to pass as the parent id and it looks like so:</p>

<pre><code>locolhost/store.php?c=2
</code></pre>

<p>the navigation I'm looking for should look like:</p>

<pre><code>Parent
    child
    child
Parent
Parent
Parent
</code></pre>

<p>but, currently my code produces:</p>

<pre><code>Parent
    child
    child
Parent
    child
    child
Parent
    child
    child
Parent
    child
    child
</code></pre>

<p>Here's my current code:</p>

<p><strong>shop.php</strong></p>

<pre><code>$parent_id = $_GET['p'];
include('navigation.php');
$navigation = new navigation;
print($navigation-&gt;main($parent_id));
</code></pre>

<p><strong>navigation.php</strong></p>

<pre><code>public function main($parent)
{
    /* PDO */
    $array = $categoryVIEW-&gt;fetchAll(PDO::FETCH_ASSOC);
    return $this-&gt;buildNav($array,$parent);
}
private function buildNav($array,$parent)
{
    $html = '';
    foreach($array as $item)
    {
        if($item['parent'] === NULL)
        {
            $html .= "\n&lt;div class=\"parent\"&gt;&lt;a href=\"?p=".$item['category_id']."\"&gt;".$item['category_name']."&lt;/a&gt;&lt;/div&gt;\n";
            $html .= "&lt;div class=\"child\"&gt;\n";
            $html .= $this-&gt;getChildren($array,$parent);
            $html .= "&lt;/div&gt;\n";
        }
    }
    return $html;
}
private function getChildren($array,$parent)
{
    $html = '';
    foreach($array as $item)
    {
        if($item['parent']===$parent)
        {
            $html .= "\t&lt;a href=\"?p=".$item['category_id']."\"&gt;".$item['category_name']."&lt;/a&gt;\n";
        }
    }
    return $html;
}
</code></pre>

<p>I'm just simply calling called <code>getChildren()</code> from <code>buildNav()</code> which gets all the children for the selected category. I think I need a condition that will call <code>getChildren()</code> only when the parent I want to show it's children is going through the loop ... if that makes sense?</p>

<p>Here's my database:</p>

<p><img src="http://i.stack.imgur.com/DXQh6.jpg" alt="enter image description here"></p>
