递归部门

部门有子部门,子部门又有子部分,后代部门无限制,数据库储存结构如datalist,通常需要构造成层次结构。

<?php

$deptlist = [
    ['id'=>'1','name'=>'名称1','pid'=>'0'],
    ['id'=>'2','name'=>'名称2','pid'=>'1'],
    ['id'=>'3','name'=>'名称3','pid'=>'1'],
    ['id'=>'4','name'=>'名称4','pid'=>'3'],
    ['id'=>'5','name'=>'名称5','pid'=>'3'],
    ['id'=>'6','name'=>'名称6','pid'=>'5'],
    ['id'=>'7','name'=>'名称7','pid'=>'5'],
    ['id'=>'8','name'=>'名称8','pid'=>'0'],
    ['id'=>'9','name'=>'名称9','pid'=>'8'],
    ['id'=>'10','name'=>'名称10','pid'=>'8'],
];


function getDeptbyPid($arr,$pid){
    $filtered = array_filter($arr, function($item) use ($pid) {
        return $item['pid'] == $pid;
    });
    return $filtered;

}

$topdepts = getDeptbyPid($deptlist,'0');

foreach ($topdepts as &$v){
    $v['son'] = getSonDept($deptlist,$v['id']);
}


function getSonDept($arr,$pid){
    $dpets = getDeptbyPid($arr,$pid);
    foreach ($dpets as &$v){
        $v['son'] = getSonDept($arr,$v['id']);
    }

    return $dpets;
}

print_r($topdepts);

结果

{
    "0": {
        "id": "1",
        "name": "名称1",
        "pid": "0",
        "son": {
            "1": {
                "id": "2",
                "name": "名称2",
                "pid": "1",
                "son": []
            },
            "2": {
                "id": "3",
                "name": "名称3",
                "pid": "1",
                "son": {
                    "3": {
                        "id": "4",
                        "name": "名称4",
                        "pid": "3",
                        "son": []
                    },
                    "4": {
                        "id": "5",
                        "name": "名称5",
                        "pid": "3",
                        "son": {
                            "5": {
                                "id": "6",
                                "name": "名称6",
                                "pid": "5",
                                "son": []
                            },
                            "6": {
                                "id": "7",
                                "name": "名称7",
                                "pid": "5",
                                "son": []
                            }
                        }
                    }
                }
            }
        }
    },
    "7": {
        "id": "8",
        "name": "名称8",
        "pid": "0",
        "son": {
            "8": {
                "id": "9",
                "name": "名称9",
                "pid": "8",
                "son": []
            },
            "9": {
                "id": "10",
                "name": "名称10",
                "pid": "8",
                "son": []
            }
        }
    }
}

其中

$topdepts = getDeptbyPid($deptlist,'0');

foreach ($topdepts as &$v){
    $v['son'] = getSonDept($deptlist,$v['id']);
}

可以简化为

getSonDept($deptlist,'0')
原文地址:https://www.cnblogs.com/jimzbom/p/7790368.html