/**
* @param array $data
* @param int $id 根节点
* @param int $level 当前层级 默认初始层级为1
* @param string $parentIdName 父级字段名
* @param string $idName 主键名
* @return array
*/
public static function arrayToTree(array $data, int $id, string $parentIdName = 'parent_id', string $idName = 'id', int $level = 1): array
{
$result = [];
foreach ($data as &$item) {
if ($id == $item[$parentIdName]) {
$item['level'] = $level;
$level++;
$item['children'] = self::arrayToTree($data, $item[$idName], $parentIdName, $idName, $level);
$level--;
$item['index'] = count($result) + 1;
$result[] = $item;
}
}
return $result;
}
/**
* 获取树的深度
* @param $tree
* @param string $childrenName
* @return int|mixed
*/
public static function getTreeDeep($tree, string $childrenName = 'children')
{
$deep = 0;
foreach ($tree as $node) {
if (isset($node[$childrenName])) {
$deep = max($deep, self::getTreeDeep($node[$childrenName], $childrenName) + 1);
}
}
return $deep;
}
/**
* 树结构的数组转数组
* @param array $tree
* @param array $result
* @param string $childrenName
* @return array
*/
public static function treeToArray(array $tree, array $result = [], string $childrenName = 'children'): array
{
foreach ($tree as $iTree) {
$result[] = $iTree;
if (!empty($iTree[$childrenName])) {
$result = self::treeToArray($iTree[$childrenName], $result);
}
}
return $result;
}
PHP实现树与数组的转换
最新推荐文章于 2024-06-20 23:57:10 发布