简单实现无限极

<?php
function generateTree($array)
{
    //第一步 构造数据
    $items = array();
    foreach ($array as $value) {
        $items[$value['id']] = $value;
    }
    //第二步 遍历数据 生成树状结构
    $tree = array();
    foreach ($items as $key => $item) {
        if (isset($items[$item['pid']])) {
            $items[$item['pid']]['son'][] = &$items[$key];
        } else {
            $tree[] = &$items[$key];
        }
    }
    return $tree;
}
$array = [
    [
        'id' => 1,
        'pid' => 0,
    ],
    [
        'id' => 2,
        'pid' => 1,
    ],
    [
        'id' => 3,
        'pid' => 2,
    ],
    [
        'id' => 4,
        'pid' => 3,
    ],
    [
        'id' => 5,
        'pid' => 4,
    ],
    [
        'id' => 6,
        'pid' => 5,
    ],
    [
        'id' => 7,
        'pid' => 6,
    ],
    [
        'id' => 8,
        'pid' => 7,
    ],
    [
        'id' => 9,
        'pid' => 8,
    ],
    [
        'id' => 10,
        'pid' => 9,
    ],
];
$getTree = generateTree($array);
print_r($getTree);

💫 评论卡

备案号:粤ICP备18155514号-2