You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将组织架构数据库查询结果整理为层级数组?

实现方法

你可以通过遍历查询结果,将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:10:45