refactor: 修改array_to_tree函数所在文件

This commit is contained in:
2025-04-07 15:45:39 +08:00
parent c3d4498794
commit 4d7b6bbc03
2 changed files with 34 additions and 34 deletions

View File

@@ -1,40 +1,6 @@
<?php <?php
// 这是系统自动生成的公共文件 // 这是系统自动生成的公共文件
if (!function_exists('array_to_tree')) {
/**
* 数组转换为树状结构
* @param array $data 数据
* @param int $pid 父级ID
* @param string $with 转换依据字段
* @param int|bool $level 层级
* @param bool $keep_pid 是否保留pid
* @return array
*/
function array_to_tree(array $data, int $pid, string $with = 'pid', int|bool $level = 1, bool $keep_pid = true)
{
$ret = [];
foreach ($data as $item) {
if ($item[$with] == $pid) {
$lv = $level;
if ($level !== false) {
$item['level'] = $level;
$lv = $level + 1;
}
if ($keep_pid === false) {
unset($item[$with]);
}
$children = array_to_tree($data, $item['id'], $with, $lv, $keep_pid);
if ($children) {
$item['children'] = $children;
}
$ret[] = $item;
}
}
return $ret;
}
}
if (!function_exists('xlsx_reader')) { if (!function_exists('xlsx_reader')) {
/** /**
* 读取Excel数据 * 读取Excel数据

View File

@@ -68,4 +68,38 @@ if (!function_exists('random_str')) {
} }
return $res; return $res;
} }
}
if (!function_exists('array_to_tree')) {
/**
* 数组转换为树状结构
* @param array $data 数据
* @param int $pid 父级ID
* @param string $with 转换依据字段
* @param int|bool $level 层级
* @param bool $keep_pid 是否保留pid
* @return array
*/
function array_to_tree(array $data, int $pid, string $with = 'pid', int|bool $level = 1, bool $keep_pid = true)
{
$ret = [];
foreach ($data as $item) {
if ($item[$with] == $pid) {
$lv = $level;
if ($level !== false) {
$item['level'] = $level;
$lv = $level + 1;
}
if ($keep_pid === false) {
unset($item[$with]);
}
$children = array_to_tree($data, $item['id'], $with, $lv, $keep_pid);
if ($children) {
$item['children'] = $children;
}
$ret[] = $item;
}
}
return $ret;
}
} }