如何从含公共值的数组列表构建符合层级的嵌套数组?
问题:从分散数组生成指定层级的嵌套结构
给定层级结构:
group |__unit |__department |__team
能否从一组分散的关联数组生成匹配上述层级的嵌套数组?
示例输入
[ ["group" => "group2"], ["group" => "group2", "unit" => "unit11", "department" => "department50", "team" => "team10"], ["group" => "group2", "unit" => "unit11", "department" => "department50", "team" => "team58"], ["group" => "group2", "unit" => "unit10"], ["group" => "group5", "unit" => "unit23"], ["group" => "group5", "unit" => "unit23", "department" => "department101"] ]
期望输出
[ "group2" => [ "unit11" => [ "department50" => [ ["team10"], ["team58"] ], ], "unit10" => [], ], "group5" => [ "unit23" => [ "department101" => [] ], ], ]
解决方案
可以通过按层级顺序遍历构建的方式实现,核心思路是沿着group -> unit -> department -> team的层级路径,逐个输入项逐层创建嵌套节点,最后一层单独处理元素添加。
PHP 实现代码
<?php $input = [ ["group" => "group2"], ["group" => "group2", "unit" => "unit11", "department" => "department50", "team" => "team10"], ["group" => "group2", "unit" => "unit11", "department" => "department50", "team" => "team58"], ["group" => "group2", "unit" => "unit10"], ["group" => "group5", "unit" => "unit23"], ["group" => "group5", "unit" => "unit23", "department" => "department101"] ]; $output = []; // 定义固定层级顺序 $hierarchy = ['group', 'unit', 'department', 'team']; foreach ($input as $item) { $current = &$output; $levelIndex = 0; foreach ($hierarchy as $level) { // 当前输入项没有该层级的键,停止向下构建 if (!isset($item[$level])) { break; } $value = $item[$level]; $levelIndex++; // 处理最后一层team,直接添加为子元素 if ($level === 'team') { if (!is_array($current)) { $current = []; } $current[] = [$value]; break; } // 非最后一层,确保当前节点存在 if (!isset($current[$value])) { $current[$value] = []; } // 移动到下一层级的引用 $current = &$current[$value]; } // 对于不完整的层级(如只有group/unit),保持节点为空数组 if ($levelIndex < count($hierarchy) && empty($current)) { $current = []; } } print_r($output); ?>
代码说明
- 先定义固定的层级顺序
$hierarchy,明确嵌套的先后逻辑 - 遍历每个输入项,通过引用
&$current跟踪当前构建的嵌套位置,避免重复遍历整个结构 - 逐层检查输入项是否包含当前层级的键,存在则创建或进入对应节点
- 最后一层
team单独处理,直接将其包装为数组添加到对应父节点中 - 对于不完整的层级(如只有group或unit的输入项),确保对应节点为空数组,符合期望格式
内容的提问来源于stack exchange,提问作者pileup
相关产品推荐
相关产品推荐

