Code examples for PHP Infinitus classification (recursive and tree)

不言
Release: 2023-04-05 07:28:02
forward
1731 people have browsed it

This article brings you code examples (recursion and trees) of PHP Infinitus classification. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

(1) .Recursive implementation

function getTree($array, $pid =0, $level = 0){
//声明静态数组,避免递归调用时,多次声明导致数组覆盖 
static $list = []; 
foreach ($array as $key => $value){     
//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点  
if ($value['pid'] == $pid){
//父节点为根节点的节点,级别为0,也就是第一级
$value['level'] = $level;
//把数组放到list中
$list[] = $value;
//把这个节点从数组中移除,减少后续递归消耗           
unset($array[$key]);           
//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1          
getTree($array, $value['id'], $level+1);
        }
    } 
return $list;
}
Copy after login

The result is as shown in the figure:

(2) .Tree structure

function getTree($items,$pid ="pid") {
    $map  = [];
    $tree = []; 
foreach ($items as &$it){ $map[$it['id']] = &$it; }  
//数据的ID名生成新的引用索引树   
foreach ($items as &$at){
        $parent = &$map[$at[$pid]];    
if($parent) {
            $parent['children'][] = &$at;
        }else{
            $tree[] = &$at;
        }
    }
return $tree;
}
Copy after login

The result is as shown:

The above is the detailed content of Code examples for PHP Infinitus classification (recursive and tree). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template