当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
百度地图案例-修改地图样式
Scientists say Australian plan to cull up to 10,000 wild horses doesn’t go far enough
Method of MySQL password expiration
PHP 无限极分类和树形
Overview of node file system and buffer
SignalR实现从服务端主动发送数据到客户端
leetcode刷题之整数加一
柯里化实现函数连续调用计算累加和
.Net Core 下使用 Quartz —— 【3】作业和触发器之作业传参
浏览器工作原理与实践
.Net Core 下使用 Quartz —— 【6】作业和触发器之触发器的日历
浏览器中堆栈内存的底层处理
TypeScript(下)
数据可视化基础了解
ASP.NET CORE配置选项(下篇)
Analysis of fixed point PID code of FOC motor Library
微信小程序
Mailbox string judgment
2021-09-18
【批量更改mysql表以及表中字段对应的编码】