当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
手动实现call,apply,bind函数
New features of ES6
Promise(三)
C language structure specifying initialization
ASP.NET CORE JWT认证
SiteServer CMS5.0使用总结
Node accesses server-side static resources
浏览器工作原理与实践
Parse PSD files and map them into components
批量修改/批量更新数据库某一个字段的值
自用学习笔记-connectingString配置
leetcode刷题之整数加一
Leak detection and filling (I)
启用AHCI后无法启动系统
sql中的 IF 条件语句的用法
ASP.NET CORE3.1 Identity注册用户后登录失败的解决方案
Oracle改成mysql
input文件上传
TypeScript(下)
【Markdown笔记】









