Files
account/app/Support/Tree.php
2026-01-18 09:52:48 +08:00

89 lines
2.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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;
}
}