如何将组织架构数据库查询结果整理为层级数组?
实现方法
你可以通过遍历查询结果,将null替换为other后,按group -> branch -> unit的层级逐步构建目标数组,以下是两种可行的实现方式:
方式一:foreach循环(直观易懂)
直接遍历集合中的每一项,逐层初始化数组并填充数据:
$result = []; foreach ($data as $item) { // 将null替换为"other" $group = $item->group ?? 'other'; $branch = $item->branch ?? 'other'; $unit = $item->unit ?? 'other'; // 初始化group层级 if (!isset($result[$group])) { $result[$group] = []; } // 初始化branch层级 if (!isset($result[$group][$branch])) { $result[$group][$branch] = []; } // 添加unit(因已通过GROUP BY去重,无需额外判重) $result[$group][$branch][] = $unit; }
方式二:Laravel集合reduce方法(优雅简洁)
利用集合的reduce方法链式处理,直接构建层级结构:
$result = $data->reduce(function ($carry, $item) { $group = $item->group ?? 'other'; $branch = $item->branch ?? 'other'; $unit = $item->unit ?? 'other'; // 逐层填充数组 $carry[$group][$branch][] = $unit; return $carry; }, []);
说明
因为你已经通过GROUP BY 'group', 'branch', 'unit'做了去重处理,所以每个层级组合只会出现一次,无需额外处理重复的unit值。执行后得到的数组结构完全符合你的需求。
内容的提问来源于stack exchange,提问作者pileup
相关产品推荐
相关产品推荐

