PHP 在PHP中创建树结构

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 在PHP中创建树结构相关的知识,希望对你有一定的参考价值。

<?php
class Node
{
    public $depth = 0;          //for printing
    public $parentNode = null;  //reference to parent node
    public $text = '';          //display text
    public $children = array(); //children node(s)
    
    function __construct($params = null)
    {
        foreach($params as $key=>$val)
            $this->$key = $val;
        if (isset($this->parentNode))
            $this->parentNode->addChild($this);
    }
    public function addChild(Node $node)
    {
        $this->children[] = $node;
    }
}
//-------------- end of class Node
class Tree
{
    public $root = null;
    
    function __construct($maxLevel = 3)
    {
        $this->buildTree($maxLevel);
    }
    
    public function buildTree($maxLevel = 3)
    {
        $this->root = new Node(array('text'=>'Root'));
        $this->populateChildren($this->root, 1, $maxLevel);
    }
    
    public function printNodes()
    {
        $this->printChildren($this->root);
    }
    
    private function printChildren(Node $node)
    {
        $N = $node->depth * 4;
        for ($idx = 0; $idx < $N; $idx++)
            echo ' ';
            
        echo $node->text . "<br />\n";
        foreach($node->children as $child)
            $this->printChildren($child);
    }
    
    private function populateChildren(Node $pnode, $level, $maxLevel)
    {
        //demonstrate how to populate tree's node
        if ($level <= $maxLevel)
        {
            for($idx = 0; $idx < $level; $idx++)
            {
                $child = new Node(array(
                    'parentNode'=> $pnode, 
                    'text' => "$level::Node[$idx]", 
                    'depth'=>$level)
                );
                $this->populateChildren($child, $level + 1, $maxLevel);
            }
        }
    }	
}
//-------------- end of class Tree

//test displaying tree
$tree = new Tree(4);
$tree->printNodes();

以上是关于PHP 在PHP中创建树结构的主要内容,如果未能解决你的问题,请参考以下文章

在java中创建树数据结构?

在 PHP 中创建一个包罗万象的处理程序?

PHP数据结构-完全二叉树线索二叉树及树的顺序存储结构

如何在java中创建树型对象? [复制]

PHP数据结构-完全二叉树线索二叉树及树的顺序存储结构

Laravel - 在web.php以外的文件中创建路由