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; }
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; }
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!