当前位置:网站首页>PHP unlimited classification and tree
PHP unlimited classification and tree
2022-04-23 06:52:00 【Collect and study by yourself】
PS: I don't know how to traverse the tree without limit , I feel that it is only suitable for defining the total number of layers , For example, one 、 Two 、 Three level menu , Not suitable for infinite
Infinite classification ( Recursive method ):
/*
Recursive infinite classification
*/
function unlimitedMenu($arr,$pid=0,$level=0){
static $list = array();
foreach ($arr as $v) {
// If it's a top-level category , Then save it to $list in , And take this node as the root node , Traversing its child nodes
if ($v['pid'] == $pid) {
$v['level'] = $level;
$list[] = $v;
unlimitedMenu($arr,$v['id'],$level+1);
}
}
return $list;
}
Tree menu ( One ):
/*
The array returns a tree structure
$id Self increasing ID Field name
$pid Parent class id Field name
$son Key name of subset
*/
function tree($array,$id='id',$pid='pid',$son='son'){
$temp = [];
foreach ($array as $v) {
$v[$son] = [];
$temp[$v[$id]] = $v;
}
// Get classification tree
foreach ($temp as $k => $v) {
$temp[$v[$pid]][$son][] = &$temp[$v[$id]];
}
return isset($temp[0][$son]) ? $temp[0][$son] : [];
}
Tree menu ( Two ):
function getChild($data, $id = 0)
{
// Initialize son
$child = [];
// Cycle all data to find $id Son
foreach ($data as $key => $datum) {
// I found my son
if ($datum['pid'] == $id) {
// preserved , Then continue to find his son's son
$child[$datum['id']] = $datum;
// Get rid of yourself first , You can't be your own grandchildren
unset($data[$key]);
// Recursively look for , And put the found son in a child In the field of
$child[$datum['id']]['child'] = getChild($data, $datum['id']);
}
}
return $child;
}
版权声明
本文为[Collect and study by yourself]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555551949.html
边栏推荐
猜你喜欢

TP5 error reporting variable type error: array solution

ASP.NET CORE3.1 Identity注册用户后登录失败的解决方案

EF CORE在ASP.NET CORE项目中基于数据库优先模式生成实体模型

freeCodeCamp----arithmetic_arranger练习

ASP.NET CORE JWT认证

leetcode刷题之二进制求和

Devexpress Gridview 添加全选列

1-1 NodeJS

Kids and COVID: why young immune systems are still on top

关于软件的空间占用,安装目录
随机推荐
百度地图案例-缩放组件、地图比例组件
New formdata() when importing files
window环境下使用小皮面板安装redis
Leak detection and vacancy filling (IV)
leetcode刷题之x的算术平方根
Overview of node file system and buffer
.Net Core 下使用 Quartz —— 【3】作业和触发器之作业传参
DNA reveals surprise ancestry of mysterious Chinese mummies
自用学习笔记-connectingString配置
offset和client獲取dom元素比特置信息
Database programming of node
几款笔记软件的优缺点
file_ get_ Two solutions to content accessing SSL errors
时间格式不对,运行sql文件报错
Color string conversion
New type of dark energy could solve Universe expansion mystery
并发优化请求
The difference between VaR, let and Const
file_get_contents 访问 ssl 错误的两种解决方法
浏览器中堆栈内存的底层处理