first commit
This commit is contained in:
88
app/Support/Tree.php
Normal file
88
app/Support/Tree.php
Normal file
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
|
||||
// +----------------------------------------------------------------------
|
||||
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
|
||||
// +----------------------------------------------------------------------
|
||||
namespace App\Support;
|
||||
|
||||
class Tree {
|
||||
|
||||
public static function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $children = 'children') {
|
||||
// 创建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
|
||||
$parentId = 0;
|
||||
if (isset($data[$pid])) {
|
||||
$parentId = $data[$pid];
|
||||
}
|
||||
if ((string)$root == $parentId) {
|
||||
$tree[] = &$list[$key];
|
||||
} else {
|
||||
if (isset($refer[$parentId])) {
|
||||
$parent = &$refer[$parentId];
|
||||
$parent[$children][] = &$list[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $tree;
|
||||
}
|
||||
|
||||
public static function tree_to_list($tree = [], $children = 'children') {
|
||||
if (empty($tree) || !is_array($tree)) {
|
||||
return $tree;
|
||||
}
|
||||
$arrRes = [];
|
||||
foreach ($tree as $k => $v) {
|
||||
$arrTmp = $v;
|
||||
unset($arrTmp[$children]);
|
||||
$arrRes[] = $arrTmp;
|
||||
if (!empty($v[$children])) {
|
||||
$arrTmp = self::tree_to_list($v[$children], $children);
|
||||
$arrRes = array_merge($arrRes, $arrTmp);
|
||||
}
|
||||
}
|
||||
return $arrRes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得所有的子
|
||||
*/
|
||||
public static function get_children($data, $id = 0, $pk = 'id', $pid = 'parent_id') {
|
||||
$array = [];
|
||||
foreach ($data as $k => $v) {
|
||||
if ($v[$pid] == $id) {
|
||||
$array[] = $v[$pk];
|
||||
array_merge($array, self::get_children($data, $v[$pk], $pk, $pid));
|
||||
}
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取id的所有父,包含自己
|
||||
*/
|
||||
public static function get_parents($data, $id = 0, $pk = 'id', $pid = 'parent_id', $field = '') {
|
||||
$temp = [];
|
||||
foreach ($data as $k => $v) {
|
||||
if ($v[$pk] == $id) {
|
||||
$temp[] = $v;
|
||||
$temp = array_merge($temp, self::get_parents($data, $v[$pid]), $pk, $pid, $field);
|
||||
}
|
||||
}
|
||||
if($field){
|
||||
$temp = array_column($temp, $field);
|
||||
}
|
||||
return $temp;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user