使用递归构建导航 [英] Using recursion to build navigation

查看:57
本文介绍了使用递归构建导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building navigation for a site and for the life of me I can't figure out recursion. I have all my data stored via MySQL using this design:

我已经阅读了几个有关递归工作方式的链接,但我必须慢一点,因为这对我来说很难理解.我已经尝试过写一些东西,但我知道它甚至与我真正需要的东西都不尽相同,但这只是一个开始:

I've read several links on how recursion works and I must be slow because it's difficult for me to grasp. I've tried to write something and I know it is not even close to what I really need, but it's a start:

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);

按预期,这将永远不会进入条件.我确实尝试自己解决这个问题,因为了解这是一件好事,但我想这超出了我的思维能力:(

as expected this will never enter the condition. I did try to figure this out on my own since this is a good thing to have knowledge of, but I guess it's beyond my mental capacity :(

感谢您的光临:)

更新

我知道已经回答了这个问题,但是有什么办法可以建立一个关联数组?我一直在尝试从 HERE ,但是它添加了一个我不想要的额外数组.

I know this has been answered already, but is there a way I can do this to build an associative array? I have been playing around with a function that ALMOST works for me that I got from HERE, but it adds an extra array that I do NOT want.

方法

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":[]}

推荐答案

以下是递归示例.

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>

这篇关于使用递归构建导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆