发布于 5年前

php 生成无限Tree结构

代码:

$arrs = [
    [
        'id'=>1,
        'parent_id'=>0
    ],
    [
        'id'=>2,
        'parent_id'=>1
    ],
    [
        'id'=>3,
        'parent_id'=>2
    ],
    [
        'id'=>4,
        'parent_id'=>2
    ],
    [
        'id'=>5,
        'parent_id'=>0
    ],
    [
        'id'=>6,
        'parent_id'=>5
    ],
];
var_export(getTree($arrs,0,2));
function getTree($arrs,$root=0,$level=100)
{
    $tree = array();
    foreach ($arrs as &$foo) {
        if ($foo['parent_id'] == $root) {

           if($level>0){

            $foo['children'] = getTree($arrs,$foo['id'],$level-1);

           }
            $tree[] = $foo;
             unset($foo);

        }
    }
    --$level;
    return $tree;
}

输出:

array (
  0 => 
  array (
    'id' => 1,
    'parent_id' => 0,
    'children' => 
    array (
      0 => 
      array (
        'id' => 2,
        'parent_id' => 1,
        'children' => 
        array (
          0 => 
          array (
            'id' => 3,
            'parent_id' => 2,
          ),
          1 => 
          array (
            'id' => 4,
            'parent_id' => 2,
          ),
        ),
      ),
    ),
  ),
  1 => 
  array (
    'id' => 5,
    'parent_id' => 0,
    'children' => 
    array (
      0 => 
      array (
        'id' => 6,
        'parent_id' => 5,
        'children' => 
        array (
        ),
      ),
    ),
  ),
)
©2020 edoou.com   京ICP备16001874号-3