使用递归来构建导航

时间:2012-10-21 21:22:03

标签: php mysql recursion

我正在为一个网站构建导航,而对于我的生活,我无法弄清楚递归。我使用这种设计通过MySQL存储了所有数据:

enter image description here

我已经阅读了几个关于递归如何工作的链接,我一定很慢,因为我很难掌握。我试着写一些东西,我知道它甚至不是我真正需要的东西,但它是一个开始:

PDO

public function viewCategories()
{
    $viewSQL = "SELECT * FROM categories";  
    try
    {
        $pdo = new PDO('mysql:host=localhost;dbname=store','root','');
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $categoryVIEW = $pdo->prepare($viewSQL);
        $categoryVIEW->execute();
        $array = $categoryVIEW->fetchAll(PDO::FETCH_ASSOC);
        $categoryVIEW->closeCursor();
        $json = json_encode($array);
        return $json;
    }
    catch(PDOexception $e)
    {
        return $e->getMessage();
        exit();
    }
}

递归

$return = json_decode($category->viewCategories(),true);

function buildNavigation($json)
{
    foreach($json as $item)
    {
        if($item['category_id'] === $item['parent'])
        {
            print('<li>'.$item['category_name'].'</li>');
            if($item['category_id'] === $item['parent'])
            {
                print('<li>match'.$item['category_name'].'</li>');
                buildNavigation($json);
            }
        }
}
buildNavigation($return);

如预期的那样永远不会进入这个状态。我确实试图通过自己来解决这个问题,因为知道这是一件好事,但我想这超出了我的心理能力:(

感谢您一看:)

更新

我知道这已经得到了回答,但有没有办法建立一个关联数组呢?我一直在使用ALMOST为我工作的函数,我从 HERE 获取,但它添加了一个我不想要的额外数组。

方式

private function buildCategories($array,$parent)
{
    $result = array();
    foreach($array as $row)
    {
        if($row['parent'] == $parent)
        {
            $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']);
        }
    }
    return $result;
}
$json = json_encode($this->buildCategories($array,NULL));
return $json;

我想要这个:

{"reloading":{"components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"}

但我得到的是:

{"reloading":{"components":[],"presses and dies":[],"tumblers & scales":[],"tools & accessories":[],"shotshell reloading":[]}

2 个答案:

答案 0 :(得分:15)

以下是递归的示例。

function buildNavigation($items, $parent = NULL)
{
    $hasChildren = false;
    $outputHtml = '<ul>%s</ul>';
    $childrenHtml = '';

    foreach($items as $item)
    {
        if ($item['parent'] == $parent) {
            $hasChildren = true;
            $childrenHtml .= '<li>'.$item['category_name'];         
            $childrenHtml .= buildNavigation($items, $item['category_id']);         
            $childrenHtml .= '</li>';           
        }
    }

    // Without children, we do not need the <ul> tag.
    if (!$hasChildren) {
        $outputHtml = '';
    }

    // Returns the HTML
    return sprintf($outputHtml, $childrenHtml);
}

print buildNavigation($items);

该脚本产生以下输出:

<ul>
    <li>Menu 1</li>
    <li>Menu 2
        <ul>
            <li>Sub Menu 2.1</li>
            <li>Sub Menu 2.2</li>
            <li>Sub Menu 2.3
                <ul>
                    <li>Sub Menu 2.2.1</li>
                    <li>Sub Menu 2.2.2</li>
                    <li>Sub Menu 2.2.3</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>Menu 3</li>
</ul>

答案 1 :(得分:0)

我有相同的上面代码,只需稍加修改,以便用户可以在每个级别的菜单上应用不同的css,现在它在第一个子菜单中显示子菜单类如child-class1,它将显示child-class2在第二个子菜单中等等...

  <?php
 function buildNavigation($items, $parent = NULL, $n=NULL)
    {
$hasChildren = false;
if ($parent == NULL)
{
    $level=0;
    $outputHtml = '<ul class="parent-class">%s</ul>';
}
else
{
    if($n==NULL)
    {
        $level=1;
    }
    else
    {
        $level=$n;
    }
    $outputHtml = '<ul class="child-class'.$level.'">%s</ul>';  
} 
$childrenHtml = '';
foreach($items as $item)
{
    if ($item['parent'] == $parent) {
        $hasChildren = true;
        $childrenHtml .= '<li><a href="/'.$item['slug'].'">'.$item['ptitle'].'</a>';
        $next = ++$level;
        $childrenHtml .= buildNavigation($items, $item['pageid'],$next);         
        $childrenHtml .= '</li>';           
    }
}

// Without children, we do not need the <ul> tag.
if (!$hasChildren) {
    $outputHtml = '';
}

// Returns the HTML
return sprintf($outputHtml, $childrenHtml);
}
echo  buildNavigation($ppages);
?>

它会像这样显示出来

    <ul class="parent-class">
      <li>
        <a href="http://example.com/page-1">page 1</a>
           <ul class="child-class1">
              <li>
                 <a href="http://example.com/this-is-child-page">this is child page</a>
                  <ul class="child-class2">
                     <li>
                        <a href="http://example.com/child-of-child">child of child</a>                 </li>
                  </ul>
              </li>
          </ul>
      </li>
 </ul>

我要感谢@Maxime Morin先生。