1. 程式人生 > >無限極分類如何把 資料 遍歷成 tree 結構

無限極分類如何把 資料 遍歷成 tree 結構

關鍵
子類 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;
 }