選單的無限極分類實現

leo_qin發表於2019-02-16
/**
 * 遞迴
 */
public function getTree($data, $pk = `id`, $pid = `pid`, $child = `child`, $root = 0)
{
    $tree = array();
    foreach($data as $k => $v) {
        if($v[$pid] == $root) {
            //父親找到兒子
            $v[$child] = $this->getTree($data, $pk, $pid, $child, $v[$pk]);
            $tree[] = $v;
        }
    }
    return $tree;
}
/** 
 * 迭代
 */
public function getTree($list, $pk = `id`, $pid = `pid`, $child = `child`, $root = 0)
{
    $tree     = array();
    $packData = array();
    foreach ($list as $data) {
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key => $val) {
        if ($val[$pid] == $root) {
            //代表跟節點
            $tree[] = &$packData[$key];
        } else {
            //找到其父類
            $packData[$val[$pid]][$child][] = &$packData[$key];
        }
    }
    return $tree;
}

相關文章