
在Laravel开发中,我们经常需要获取文件系统中的所有目录。例如,Storage::disk('local')-youjiankuohaophpcnallDirectories() 方法会返回一个包含所有子目录路径的扁平化数组,其格式通常如下所示:
[ "test", "files", "files/2", "files/2/Blocks", "files/2/Blocks/thumbs", "files/shares" ]
然而,在许多应用场景中,我们可能需要将这些扁平路径转换为更直观、层级分明的多维树形结构,以便于在前端界面(如文件管理器、导航菜单)中展示。我们期望的输出结构类似:
[
["label" => "test", "path" => "test", "children" => []],
["label" => "files", "path" => "files", "children" =>
[
["label" => "2", "path" => "files/2", "children" =>
[
["label" => "Blocks", "path" => "files/2/Blocks", "children" =>
[
["label" => "thumbs", "path" => "files/2/Blocks/thumbs", "children" => []]
]
]
]
],
["label" => "shares", "path" => "files/shares", "children" => []]
]
],
]这种转换的核心挑战在于如何识别路径中的层级关系,并将其递归地组织起来。
解决此问题的关键在于利用递归函数处理层级数据,并结合Laravel Collection的强大数据处理能力来简化分组和映射操作。
我们将创建一个名为 convertPathsToTree 的递归函数。该函数的核心思想是:
以下是实现此功能的PHP代码:
<?php
use Illuminate\Support\Collection;
/**
* 将扁平化的路径列表转换为多维树形结构。
*
* @param Collection $paths 预处理后的路径集合,每个路径是一个由目录片段组成的数组。
* @param string $separator 路径分隔符,默认为 '/'。
* @param string $parent 当前节点的父路径前缀。
* @return Collection 包含树形结构节点的集合。
*/
function convertPathsToTree(Collection $paths, string $separator = '/', string $parent = ''): Collection
{
return $paths
->groupBy(function (array $parts) {
// 根据路径的第一个片段进行分组,这代表了当前层级的直接子节点
return $parts[0];
})
->map(function (Collection $partsCollection, string $key) use ($separator, $parent) {
// 提取当前分组的子路径,即移除第一个片段后的剩余部分
$childrenPaths = $partsCollection->map(function (array $parts) {
return array_slice($parts, 1); // 移除第一个片段
})->filter(); // 过滤掉空数组(即只剩下父节点自身的情况)
// 构建当前节点的数据结构
return [
'label' => (string) $key, // 当前目录的名称
'path' => $parent . $key, // 完整路径
'children' => convertPathsToTree( // 递归调用,构建子节点
$childrenPaths,
$separator,
$parent . $key . $separator // 更新父路径前缀
),
];
})
->values(); // 重置集合的键,使其成为一个从0开始的索引数组
}在调用 convertPathsToTree 函数之前,我们需要对原始的扁平化路径数据进行预处理。原始数据是字符串数组,而我们的递归函数期望每个路径都是一个由目录片段组成的数组。
假设我们有以下原始路径数据:
use Illuminate\Support\Collection;
$data = collect([
'test',
'files',
'files/2',
'files/2/Blocks',
'files/2/Blocks/thumbs',
'files/shares',
]);我们需要使用 explode() 函数将每个字符串路径拆分成数组片段:
$processedData = $data->map(function (string $item) {
return explode('/', $item);
});
/*
$processedData 现在看起来像这样:
[
['test'],
['files'],
['files', '2'],
['files', '2', 'Blocks'],
['files', '2', 'Blocks', 'thumbs'],
['files', 'shares'],
]
*/将上述步骤结合起来,我们可以轻松地将扁平路径转换为树形结构:
<?php
require 'vendor/autoload.php'; // 确保Composer自动加载
use Illuminate\Support\Collection;
/**
* 将扁平化的路径列表转换为多维树形结构。
*
* @param Collection $paths 预处理后的路径集合,每个路径是一个由目录片段组成的数组。
* @param string $separator 路径分隔符,默认为 '/'。
* @param string $parent 当前节点的父路径前缀。
* @return Collection 包含树形结构节点的集合。
*/
function convertPathsToTree(Collection $paths, string $separator = '/', string $parent = ''): Collection
{
return $paths
->groupBy(function (array $parts) {
return $parts[0];
})
->map(function (Collection $partsCollection, string $key) use ($separator, $parent) {
$childrenPaths = $partsCollection->map(function (array $parts) {
return array_slice($parts, 1);
})->filter();
return [
'label' => (string) $key,
'path' => $parent . $key,
'children' => convertPathsToTree(
$childrenPaths,
$separator,
$parent . $key . $separator
),
];
})
->values();
}
// 1. 原始路径数据(通常来自 Storage::allDirectories())
$originalPaths = collect([
'test',
'files',
'files/2',
'files/2/Blocks',
'files/2/Blocks/thumbs',
'files/shares',
]);
// 2. 预处理数据:将字符串路径拆分为数组片段
$processedPaths = $originalPaths->map(function (string $item) {
return explode('/', $item);
});
// 3. 调用函数生成树形结构
$tree = convertPathsToTree($processedPaths);
// 输出结果,使用 JSON_PRETTY_PRINT 使输出更易读,JSON_UNESCAPED_UNICODE 避免中文乱码
echo json_encode($tree->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
/*
预期输出:
[
{
"label": "test",
"path": "test",
"children": []
},
{
"label": "files",
"path": "files",
"children": [
{
"label": "2",
"path": "files/2",
"children": [
{
"label": "Blocks",
"path": "files/2/Blocks",
"children": [
{
"label": "thumbs",
"path": "files/2/Blocks/thumbs",
"children": []
}
]
}
]
},
{
"label": "shares",
"path": "files/shares",
"children": []
}
]
}
]
*/$treeArray = convertPathsToTree($processedPaths)->toArray();
通过结合Laravel Collection的强大数据处理能力和递归算法,我们成功地将扁平化的目录路径列表转换为结构清晰、易于管理和展示的多维树形数组。这种方法不仅提高了代码的可读性和维护性,也为前端展示文件系统提供了极大的便利。掌握这一技巧,将使你在处理文件目录数据时更加得心应手。
以上就是Laravel:将扁平化目录路径转换为多维树形结构教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号