php子孙树生成层级-递归篇

毫不废话,代码如下:

<?php
$list = [
    ['id' => 1, 'pid' => 0, 'name' => '江苏'],
    ['id' => 2, 'pid' => 0, 'name' => '浙江'],
    ['id' => 3, 'pid' => 1, 'name' => '苏州'],
    ['id' => 4, 'pid' => 3, 'name' => '吴中区'],
    ['id' => 5, 'pid' => 2, 'name' => '宁波'],
    ['id' => 6, 'pid' => 4, 'name' => '工业园'],
    ['id' => 7, 'pid' => 6, 'name' => '中新大道'],
    ['id' => 8, 'pid' => 5, 'name' => '鄞州区'],
    ['id' => 9, 'pid' => 8, 'name' => '天童南路'],
];

$list = get_tree($list);
foreach ($list as $key => $value) {
    echo str_repeat(" ",$value['level']) . $value['name'] . "\n";
}

function get_tree($list = [], $pid = 0, $level = 0)
{
    static $result = [];
    foreach ($list as $key => $value) {
        if ($value['pid'] == $pid) {
            $value['level'] = $level;
            $result[] = $value;
            unset($list[$key]);
            get_tree($list, $value['id'], $level+1);
        }
    }
    return $result;
}

展示结果如下:

posted @ 2022-03-25 17:05  李照耀  阅读(92)  评论(0编辑  收藏  举报