PHP返回父子级树状结构

函数get_tree_list:返回父子级树状结构

<?php
//返回 父子级树状结构
function get_tree_list($list)
{
    //将每条数据中的id值作为其下标
    $temp = [];
    foreach ($list as $v) {
        $v['son'] = [];
        $temp[$v['id']] = $v;
    }
    //获取分类树
    foreach ($temp as $k => $v) {
        //第一的数据示例$temp[0]['son'][] = $temp[1];$temp[1]['son'][] = $temp[2];$temp[1]['son'][] = $temp[3];$temp[2]['son'][] = $temp['4']
        $temp[$v['pid']]['son'][] = &$temp[$v['id']];
    }
    return isset($temp[0]['son']) ? $temp[0]['son'] : [];
}

//测试数据
$arr = [
    ['id'=>1,'name'=>'wyq1','sex'=>'男','pid'=>0],
    ['id'=>2,'name'=>'wyq2','sex'=>'男','pid'=>1],
    ['id'=>3,'name'=>'wyq3','sex'=>'男','pid'=>1],
    ['id'=>4,'name'=>'wyq4','sex'=>'男','pid'=>2],
];

$tree = get_tree_list($arr);
var_dump($tree);

返回示例

array(1) {
    [0]=>
        array(5) {
        ["id"]=>
            int(1)
            ["name"]=>
            string(4) "wyq1"
            ["sex"]=>
            string(3) "男"
            ["pid"]=>
            int(0)
            ["son"]=>
            array(2) {
            [0]=>
                array(5) {
                ["id"]=>
                    int(2)
                    ["name"]=>
                    string(4) "wyq2"
                    ["sex"]=>
                    string(3) "男"
                    ["pid"]=>
                    int(1)
                    ["son"]=>
                    array(1) {
                    [0]=>
                        array(5) {
                        ["id"]=>
                            int(4)
                            ["name"]=>
                            string(4) "wyq4"
                            ["sex"]=>
                            string(3) "男"
                            ["pid"]=>
                            int(2)
                            ["son"]=>
                            array(0) {
                        }
                    }
                }
            }
            [1]=>
                array(5) {
                ["id"]=>
                    int(3)
                    ["name"]=>
                    string(4) "wyq3"
                    ["sex"]=>
                    string(3) "男"
                    ["pid"]=>
                    int(1)
                    ["son"]=>
                    array(0) {
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值