php根据id和pid把单级数组重新组合为树结构

function list_to_trees($list, $pk='id', $pid = 'pid', $child = 'children', $root = 0) {
//创建Tree
$tree = array();
if (is_array($list)) {
//创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data){
$refer[$data[$pk]] = &$list[$key];
}
foreach ($list as $key => $data){
//判断是否存在parent
$parantId = $data[$pid];
if ($root == $parantId) {
$tree[] = &$list[$key];
}else {
if (isset($refer[$parantId])) {
$parent = &$refer[$parantId];
$parent[$child][] = &$list[$key];
}
}
}
}
return $tree;
}
参数说明
- $list [array] 原始数组
- $pk [string] id
- $pid [string] 父级pid
- $child [array] 承载子集的容器
- return [array] 返回树结构
一般传第一个参数就行
联系站长:
相关文章
js获取本月,本年,近一月,近3月,近1年的日期范围,获取近n月的日期范围
js获取本月,本年,近一月,近3月,近1年的日期范围,获取近n月的日期范围function getnMonth(i) { console.log(&quo...
js使用正则表达式获取html字符串中的img标签的src组成数组
js使用正则表达式获取html字符串中的img标签的src组成数组exec() 方法用于检索字符串中的正则表达式的匹配。如果字符串中有匹配的值返回该匹配值,否则返回 null。var htm...
【JavaScript】js获取当前年月日周
【JavaScript】js获取当前年月日周function getcurtime(){ const addZero =...
css显示三行文字,溢出显示省略号
css显示三行文字,溢出显示省略号(显示任意行,可以把数字3替换成其他数字):.text-wrap { display: -webkit-box; &n...
js获取m到n随机数,js获取随机整数,从0到10,从m到n任意数
˂a class="reference-link" name="js获取从m到n的随机数"˃js获取从m到n的随机数function getRandomNumber(min, ma...
js把数字格式化为千分位兼容版,兼容小数(8,888.22)
js把任意数字格式化为千分位/** * 格式化为千分位 * @param num 当前值字符串 * @ret...





