首先建立資料表並添加些資料
CREATE TABLE IF NOT EXISTS category ( categoryId smallint(5) unsigned NOT NULL AUTO_INCREMENT, parentId smallint(5) unsigned NOT NULL DEFAULT '0', categoryName varchar(50) NOT NULL, PRIMARY KEY (categoryId) ) ;INSERT INTO category (categoryId, parentId, categoryName) VALUES(1, 0, 'php'), (2, 0, 'java'), (3, 0, 'c/c++'), (4, 1, 'php基礎'), (5, 1, 'php開源資料'), (6, 1, 'php架構'), (7, 2, 'java Se'), (8, 2, 'java EE'), (9, 2, 'java Me'), (10, 3, 'c/c++基礎編程'), (11, 3, 'c/c++系統開發'), (12, 3, 'c嵌入式編程'), (13, 3, 'c++應用開發'), (14, 13, 'c++案頭應用開發'), (15, 13, 'c++遊戲開發');
/** *遞迴實現層級樹狀展現資料 *$tree為二位元組, *$depth為樹的最大深度,0表示不設定深度 *$rootId表示父級分類的ID *$level記錄層級樹的層數**/function arr2tree($tree,$depth,$rootId = 0,$level=1) { $return = array(); foreach($tree as $leaf) { if($leaf['parentId'] == $rootId) { $leaf['level'] = $level; foreach($tree as $subleaf) { if($subleaf['parentId'] == $leaf['categoryId'] && ($depth?$level<$depth:1)) { $leaf['children'] = arr2tree($tree,$depth,$leaf['categoryId'],$level+1); $level=1; break; } } $return[] = $leaf; } } return $return; } $tree = arr2tree($category,0);$tree1 = arr2tree($category,2);echo "";print_r($tree);print_r($tree1);
回複內容:
首先建立資料表並添加些資料
CREATE TABLE IF NOT EXISTS category ( categoryId smallint(5) unsigned NOT NULL AUTO_INCREMENT, parentId smallint(5) unsigned NOT NULL DEFAULT '0', categoryName varchar(50) NOT NULL, PRIMARY KEY (categoryId) ) ;INSERT INTO category (categoryId, parentId, categoryName) VALUES(1, 0, 'php'), (2, 0, 'java'), (3, 0, 'c/c++'), (4, 1, 'php基礎'), (5, 1, 'php開源資料'), (6, 1, 'php架構'), (7, 2, 'java Se'), (8, 2, 'java EE'), (9, 2, 'java Me'), (10, 3, 'c/c++基礎編程'), (11, 3, 'c/c++系統開發'), (12, 3, 'c嵌入式編程'), (13, 3, 'c++應用開發'), (14, 13, 'c++案頭應用開發'), (15, 13, 'c++遊戲開發');
/** *遞迴實現層級樹狀展現資料 *$tree為二位元組, *$depth為樹的最大深度,0表示不設定深度 *$rootId表示父級分類的ID *$level記錄層級樹的層數**/function arr2tree($tree,$depth,$rootId = 0,$level=1) { $return = array(); foreach($tree as $leaf) { if($leaf['parentId'] == $rootId) { $leaf['level'] = $level; foreach($tree as $subleaf) { if($subleaf['parentId'] == $leaf['categoryId'] && ($depth?$level<$depth:1)) { $leaf['children'] = arr2tree($tree,$depth,$leaf['categoryId'],$level+1); $level=1; break; } } $return[] = $leaf; } } return $return; } $tree = arr2tree($category,0);$tree1 = arr2tree($category,2);echo "";print_r($tree);print_r($tree1);
http://stackoverflow.com/questions/4196157/create-array-tree-from-array-list