tp框架中,前端頁面經常會用到無限級分類列表 和 父子級樹狀列表
//遞歸函數 實現無限級分類列表 function get_cate_list($list,$pid=0,$level=0) { static $tree = array(); foreach($list as $row) { if($row['pid']==$pid) { $row['level'] = $level; $tree[] = $row; get_cate_list($list, $row['id'], $level + 1); } } return $tree; }
//引用方式實現 父子級樹狀結構 function get_tree_list($list){ //將每條數據中的id值作為其下標 $temp = []; foreach($list as $v){ $v['son'] = []; $temp[$v['id']] = $v; } //獲取分類樹 foreach($temp as $k=>$v){ $temp[$v['pid']]['son'][] = &$temp[$v['id']]; } return isset($temp[0]['son']) ? $temp[0]['son'] : []; }
$list 需要是標准的二維數組;