【问题标题】:Recursively Generate Nested Navigation in PHP在 PHP 中递归生成嵌套导航
【发布时间】:2014-12-08 09:13:22
【问题描述】:

我有一个看起来像这样的 php 类:

class $nav_node {
    public $id;
    public $page_name;
    public $parent_id;
    public $page_content;
}

我的目标是构建一个函数,该函数采用其中一个 nav_nodes 并将其推入现有的嵌套导航结构中。

$nav_nodes = [];
function add_node($new_node) {

}

我想简单地使用html的构建嵌套导航结构

<ul> and <li> tags ( nested )

这就是结构完成后的样子

Thing
    thing2
       thing3
       thing4
    thing5
    thing6
       thing7
Thing8
    thing9

这是我的第一次尝试,但我并没有真正看到这一点。

function add_node($new_node) {
        global $nav_nodes; 

        if ( isset($nav_nodes[$new_node->id]) && !is_array($nav_nodes[$new_node->id]) ) {
            $nav_node[$new_node->id] = [];
        }

        $nav_nodes[$new_node->id][] = $new_node;

        // Display "new" nested structure    
}

我想递归可以在某处使用。我在想,即使这个功能 正确构建数组的结构,我仍然需要以某种方式显示它。 也许这是一个单独的功能?也许那个单独的显示功能就是 是递归的? 我认为如果这可以是一个单一的功能,那将是最好的。

不管怎样,谢谢你的帮助!!

【问题讨论】:

标签: php html recursion


【解决方案1】:

这是我根据http://www.jugbit.com/php/php-recursive-menu-with-1-query/ 改编的答案,这是一个非常棒的答案。非常少/简单的代码。

class nav_node {
    public $id;
    public $page_name;
    public $parent_id;
    public $page_content;
    public $items;

    public function __construct($id, $page_name, $parent_id, $page_content)
    {
        $this->id = $id;
        $this->page_name = $page_name;
        $this->parent_id = $parent_id;
        $this->page_content = $page_content;
    }
}

class nav {
    public function generate($nodes)
    {
        ob_start();
        //echo var_dump(nav::create_array($nodes));
        echo '<ul>';

        foreach ($nodes as $node)
        {
            echo '<li>'.$node->page_name.'</li>';
            if (count($node->items) > 0)
            {
                echo nav::generate($node->items);
            }
        }

        echo '</ul>';
        return ob_get_clean();
    }

    public function create_array($nodes, $parent = 0)
    {
        $out = array();
        foreach($nodes as $node){
            if($node->parent_id == $parent){
                $out[$node->id] = $node;
                $out[$node->id]->items = nav::create_array($nodes, $node->id);
            }
        }

        return $out;
    }
}

$nodes[] = new nav_node(
    1,
    'home',
    null,
    'hello world'
);
$nodes[] = new nav_node(
    2,
    'about',
    null,
    'hello world'
);
$nodes[] = new nav_node(
    3,
    'company',
    2,
    'hello world'
);
$nodes[] = new nav_node(
    4,
    'contact',
    3,
    'hello world'
);
$nodes[] = new nav_node(
    6,
    'offices',
    3,
    'hello world'
);
$nodes[] = new nav_node(
    7,
    'staff',
    3,
    'hello world'
);

//var_dump($nodes);

nav::generate(nav::create_array($nodes));

输出:

  • 首页
  • 关于
    • 公司
      • 联系方式
      • 办公室
      • 员工

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多