如何从目录ID表构建PHP目录结构数组?
问题描述
我有一张存储目录结构的数据表,包含项ID(item ID)与目录ID(DirectoryID)。其中DirectoryID关联某一项ID,代表该目录为对应父目录的子目录。示例数据如下:
# ID, DirectoryID, DirectoryName '1', '0', 'Root Dir' '2', '0', 'Another Root Dir' '3', '2', 'TESTING456' '4', '3', 'TESTING789' '5', '1', 'TESTINGMORE' '6', '4', 'RANDOM DIR'
需要使用PHP将上述数据构建为如下格式的数组:
$array = [ [2 => 'Another Root Dir',3 => 'TESTING456', 4 => 'TESTING789', 6 => 'RANDOM DIR'], [1 => 'Root Dir',5 => 'TESTINGMORE'] ];
解决方案
可以通过构建目录映射+递归扁平化分支的方式实现,具体代码如下:
// 模拟从数据库获取的原始数据 $rawData = [ ['ID' => '1', 'DirectoryID' => '0', 'DirectoryName' => 'Root Dir'], ['ID' => '2', 'DirectoryID' => '0', 'DirectoryName' => 'Another Root Dir'], ['ID' => '3', 'DirectoryID' => '2', 'DirectoryName' => 'TESTING456'], ['ID' => '4', 'DirectoryID' => '3', 'DirectoryName' => 'TESTING789'], ['ID' => '5', 'DirectoryID' => '1', 'DirectoryName' => 'TESTINGMORE'], ['ID' => '6', 'DirectoryID' => '4', 'DirectoryName' => 'RANDOM DIR'], ]; // 转换为ID为键的映射数组,方便快速查找父/子目录 $dirMap = []; foreach ($rawData as $item) { $id = (int)$item['ID']; $dirMap[$id] = [ 'parent_id' => (int)$item['DirectoryID'], 'name' => $item['DirectoryName'] ]; } // 递归收集单个目录分支并扁平化 function collectBranch($dirId, $dirMap, &$branch) { // 先存入当前目录 $branch[$dirId] = $dirMap[$dirId]['name']; // 查找并递归收集所有子目录 foreach ($dirMap as $id => $dir) { if ($dir['parent_id'] === $dirId) { collectBranch($id, $dirMap, $branch); } } } // 生成最终目标数组 $result = []; foreach ($dirMap as $id => $dir) { // 筛选根目录(parent_id为0) if ($dir['parent_id'] === 0) { $branch = []; collectBranch($id, $dirMap, $branch); $result[] = $branch; } } // 输出结果 print_r($result);
逻辑说明
- 目录映射:将原始数据转为以ID为键的数组,避免重复遍历查找,提升处理效率
- 递归收集:通过递归函数遍历每个根目录的所有子节点,直接将节点存入扁平化的分支数组
- 结果组装:遍历所有根目录,将每个根目录的完整分支数组存入最终结果
内容的提问来源于stack exchange,提问作者monrejames
相关产品推荐
相关产品推荐

