欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

无限极分类如何把 数据 遍历成 tree 结构

程序员文章站 2022-05-31 10:07:20
...

关键
子类 pid 等于 父类 id

参考网址
https://blog.csdn.net/LYPHPER/article/details/70332425

public function xuqiu333()
{
    echo '<pre>';
    $list = K::M('code/xuqiu')->chaxun();     // 查询表中数据
    $a = $this->array2level($list);
    $b = $this->arr2tree($list);
    var_dump($a);     // $a 和 $b 是两种不同结构的数据
    var_dump($b);
    die;
    // $tree = $this->tree($list);
   
}

// 方法1

function array2level($array, $pid = 0, $level = 1) 
{ 
    static $list = []; 
    foreach ($array as $v) 
    { 
        if ($v['pid'] == $pid) 
        { 
            $v['level'] = $level;
            $list[] = $v; 
            $this->array2level($array, $v['id'], $level + 1);
         }
     } 
	return $list; 
}

// 方法2

function arr2tree($tree, $rootId = 0,$level=1) 
{ 
    $return = array(); 
    foreach($tree as $leaf) 
    { 
        if($leaf['pid'] == $rootId) 
        { 
            $leaf["level"] = $level; 
            foreach($tree as $subleaf) 
            { 
                if($subleaf['pid'] == $leaf['id']) 
                { 
                    $leaf['children'] = $this->arr2tree($tree, $leaf['id'],$level+1); break; 
                } 
            } 
            $return[] = $leaf; 
        } 
    } 
    return $return;
 }
相关标签: 无限极分类