This article mainly introduces the implementation skills of PHP unordered tree. Interested friends can refer to it. I hope it will be helpful to everyone.
The example in this article describes the implementation method of PHP unordered tree, the details are as follows:
The running effect is shown in the figure below:
php code As follows:
<?php /* 用php写的无序树 */ class unorderedTree{ // 节点id计数器 protected $nodeId=0; // 树的深度 protected $depth=0; // 树的节点数, protected $nodesCount=0; // 树的度 @todo: 使其发挥作用 public $degree=" to be implent"; // 根节点id // 由于树有多种从根节点开始操作,不想每次遍历树到顶找root,用一个变量始终指向根节点 protected $rootid=null; // 子节点集合, k-v 为 nodeid=>(stdclass)node // 一些树的实现常常是采用节点和树同一class,这里节点是使用 stdclass{ data, parent, id , childrenIds} ,因我认为节点和树应为两种对象,且stdclass要轻于树的class // 节点格式说明: $this->nodes[nodeId] = new stdclass{ id ,parentId, childrenIds, data } // id: 节点id // parentId: 节点父节点id // childrenIds: 子节点的id 不想每次遍历树确定层次关系 // 注意: 节点中, #只保存其自身数据和其子节点id的集合#, 子节点的数据通过从树 $tree->nodes[ $node->childrenIds[a_child_id] ] 访问 // data: 节点中包含的数据,如节点名称等属性数据 protected $nodes=array(); // 用户自定义访问节点 protected $userVisitFunction=null; /* 分组: 类的基本函数 */ // @todo: 构造树 public function __construct(){ } // @todo: 销毁树 public function __destruct(){ unset($this->nodes) ; } //------------ 获取数据类函数--------------- // 获取树的深度, public function getTreeDepth(){ return $this->depth; } // 获取树的节点数目 public function getCount(){ return $this->NodesCount; } // 获取树的度 public function getDegree(){ // @todo: 获取树的度(因为对度暂时没什么需要就不实现了 ) return $this->degree; } //获取指定节点 public function getNode($nodeId){ if(isset($this->Nodes[$nodeId])){ return $this->Nodes[$nodeId]; } else{ return false; } } // 获取最新id public function getId(){ return $this->nodeId; } //获取指定节点高度 public function getNodeHeight($nodeId){ if( array_key_exists($nodeId, $this->nodes) ){ // 此节点已在树里,高度至少为1,每找到一个父节点+1 $height=1; // 记录此树中已经访问过的节点, 用于防止节点构造时互相parent导致此函数死循环且及时结束查找 $visitedNodesIds=array(); // 记录当前操作节点的id $cid=$nodeId; // 当前节点的父节点必须存在于此树中 // 不用递归 while( isset($cid) ) { if( !in_array($cid,$visitedNodesIds ) ){ if( $this->rootid===$cid){ //到顶,返回 return $height; } $visitedNodesIds[]=$cid; $cid= $this->nodes[ $cid ]->parentId; $height++; } else{ return false; } } return false; } else{ return false; } } //获取根节点 public function getRoot(){ return (!is_null($this->rootid) ) && $this->nodes[$this->rootid]; } //获取指定节点和其所有子节点构成的数组 //这是用于获取子树的一个关键基础操作 public function getSubNodes($nodeId){ if(isset($this->nodes[$nodeId])){ $result=array(); $toVisitNodeIds=array(); $toVisitedNodeIds[]=$nodeId; $result[]=$this->nodes[$nodeId]->id; array_shift($toVisitedNodeIds); $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$nodeId]->childrenIds); while(!empty($toVisitedNodeIds)){ $toVisitNodeId=array_shift($toVisitedNodeIds); $result[]=$this->nodes[$toVisitNodeId]->id; $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$toVisitNodeId]->childrenIds); } return $result ; } else{ return false; } } //@todo: 获取由指定节点和其所有子节点构建的子树 public function getSubTree($nodeid){ } //---------------- 数据更新 ----------------- public function setId($nodeId){ $this->nodeId=$nodeId; return $this; } // 创建不重复的(树中未被使用的) 新id public function seekId(){ $this->nodeId++; return $this->nodeId; } public function setVisitFunction($userFunction){ $this->userVisitFunction=$userFunction; } //插入子节点,默认为插在根节点下 public function insertNode($parent_id=null , $data=null){ //注意node不是class tree $node = new stdclass; $node->data = $data; //树的节点数增加 $this->nodeCount++; // 分配节点id $this->seekId(); $node->id =$this->getId(); //插入根节点 if( (is_null($parent_id)) && is_null($this->rootid)){ $node->parentId = null; $node->childrenIds = array(); $this->depth=1; $this->rootid=$node->id; $this->nodes [$node->id]=$node; return $this; } elseif( isset($this->nodes[$parent_id]) || is_null($parent_id) ){ // 插在此树已有节点下 if(is_null($parent_id)){ $parent_id=$this->rootid; } $node->parentId = $parent_id; $node->childrenIds = array(); //更新树的最大深度 $depth=$this->getNodeHeight($parent_id); $this->depth=max($depth+1, $this->depth); $this->nodes[$parent_id]->childrenIds []= $node->id; $this->nodes [$node->id]=$node; return $this; } else{ return $this; } } //insert node 的别名 public function append($parent_id=null , $data=null){ return $this->insertNode($parent_id,$data); } // --------------- 数据访问 ----- //广度优先遍历节点的别名, 全名太长了 public function b($nodeId=null){ return $this->breadthTraversal($nodeId); } // 广度优先遍历节点 public function breadthTraversal($nodeId=null){ if(is_null($this->rootid)){ die("此树为空树,不可访问"); } else{ //全部遍历 if(is_null($nodeId) || ( $this->rootid===$nodeId) ){ $nodeId=$this->rootid; } $toVisitNodeIds=array(); $toVisitedNodeIds[]=$nodeId; $this->visit( $this->nodes[$nodeId]); array_shift($toVisitedNodeIds); $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$nodeId]->childrenIds); while(!empty($toVisitedNodeIds)){ $toVisitNodeId=array_shift($toVisitedNodeIds); $this->visit( $this->nodes[$toVisitNodeId]); $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$toVisitNodeId]->childrenIds); } } return $this; } //深度优先的别名 public function d($nodeId=null){ return $this->depthTraversall($nodeId); } // 深度优先遍历 // 和广度优先的不同实现只在于array_merge的顺序不同而已 ( php array 忒好用啊忒好用 ) public function depthTraversall($nodeId=null){ if(is_null($this->rootid)){ die("此树为空树,不可访问"); } else{ //全部遍历 if(is_null($nodeId)){ $nodeId=$this->rootid; } $toVisitNodeIds=array(); $toVisitedNodeIds[]=$nodeId; $this->visit( $this->nodes[$nodeId]); array_shift($toVisitedNodeIds); $toVisitedNodeIds=array_merge( $this->nodes[$nodeId]->childrenIds, $toVisitedNodeIds ); while(!empty($toVisitedNodeIds)){ $toVisitNodeId=array_shift($toVisitedNodeIds); $this->visit( $this->nodes[$toVisitNodeId]); $toVisitedNodeIds=array_merge( $this->nodes[$toVisitNodeId]->childrenIds, $toVisitedNodeIds ); } } return $this; } //访问单个节点 public function visit($node){ if(is_null($this->userVisitFunction )){ return $node->id; } else{ return call_user_func($this->userVisitFunction,$node,$this); } } } ?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Basic knowledge and application of PHP design patterns
Definition and generation method of PHP barcode
Several methods for php to determine and obtain file extensions
The above is the detailed content of Implementation skills of php unordered tree. For more information, please follow other related articles on the PHP Chinese website!

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use