0

我正在尝试构建一个导航,当用户选择一个类别时,导航将只显示所选类别的子类别。

我从 URL 中获取一个变量作为父 ID 传递,它看起来像这样:

locolhost/store.php?c=2

我正在寻找的导航应该如下所示:

Parent
    child
    child
Parent
Parent
Parent

但是,目前我的代码产生:

Parent
    child
    child
Parent
    child
    child
Parent
    child
    child
Parent
    child
    child

这是我当前的代码:

shop.php

$parent_id = $_GET['p'];
include('navigation.php');
$navigation = new navigation;
print($navigation->main($parent_id));

导航.php

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

我只是简单地调用 callgetChildren()从中buildNav()获取所选类别的所有子项。我想我需要一个条件,getChildren()只有当我想展示它的孩子的父母正在经历循环时才会调用......如果这有意义吗?

这是我的数据库:

在此处输入图像描述

4

2 回答 2

1

我认为您没有将正确的“父”变量传递给子函数。尝试以下操作:

private function buildNav($array,$parent)
{
    $html = '';
    foreach($array as $item)
    {
        if($item['parent'] === NULL)
        {
            $html .= "\n<div class=\"parent\"><a href=\"?p=".$item['category_id']."\">".$item['category_name']."</a></div>\n";
            $html .= "<div class=\"child\">\n";
            // the following line needs to be changed
            $html .= $this->getChildren($array,$item['category_id']);
            $html .= "</div>\n";
        }
    }
    return $html;
}
于 2012-10-29T04:58:25.937 回答
0

我想通了......我需要添加一个条件。这是工作代码:

private function buildNav($array,$parent)
{
    $html = '';
    foreach($array as $item)
    {
        if($item['parent'] === NULL)
        {
            $html .= "\n<div class=\"parent\"><a href=\"?p=".$item['category_id']."\">".$item['category_name']."</a></div>\n";
            $html .= "<div class=\"child\">\n";

            /* had to add this condition */
            if($item['category_id'] === $parent)
            {
                $html .= $this->getChildren($array,$parent);
            }               
            $html .= "</div>\n";
        }
    }
    return $html;
}
private function getChildren($array,$parent)
{
    $html = '';
    foreach($array as $item)
    {
        if($item['parent'] === $parent)
        {
            $html .= "\t<a href=\"?p=".$item['category_id']."\">".$item['category_name']."</a>\n";
        }           
    }
    return $html;
}
于 2012-10-30T00:50:12.503 回答