close

<?
//jwu 2014/8/1 多階選單可用
/*
[PHP+MYSQL] 產生多階樹狀選單 UL,LI包覆 - tree menu, Multi-Level,Recursive,array
產生格式
<ul>
<li id='tree_2'>A
<ul>
<li id='tree_1'>A1
<ul>
<li id='tree_7'>A11</li>
</ul>
</li>
<li id='tree_8'>A2</li>
</ul>
</li>
<li id='tree_3'>B
<ul>
<li id='tree_4'>B1</li>
<li id='tree_5'>B2
<ul>
<li id='tree_6'>B21</li>
</ul>
</li>
</ul>
</li>
</ul>

--
-- 資料表格式: `treeview_items`
--

CREATE TABLE `treeview_items` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(200) NOT NULL,
`title` varchar(200) NOT NULL,
`parent_id` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- 列出以下資料庫的數據: `treeview_items`
--

INSERT INTO `treeview_items` VALUES (1, 'A1', 'task1title', '2');
INSERT INTO `treeview_items` VALUES (2, 'A', 'task2title', '0');
INSERT INTO `treeview_items` VALUES (3, 'B', 'task1title3', '0');
INSERT INTO `treeview_items` VALUES (4, 'B1', 'task2title4', '3');
INSERT INTO `treeview_items` VALUES (5, 'B2', 'task1title4', '3');
INSERT INTO `treeview_items` VALUES (6, 'B21', 'task2title5', '5');

*/

$systemPageCategories = array(
array(
'id' => 1,
'name' => 'dev',
'parent_id' => 0
),

array(
'id' => 2,
'name' => 'php',
'parent_id' => 1
),
array(
'id' => 3,
'name' => 'smarty',
'parent_id' => 2
),
array(
'id' => 4,
'name' => 'life',
'parent_id' => 0
)
);
//build Tree structure from array
$data = array(
0 => array(
'id' => '1',
'parent_id' => '0',
'name' => 'A',
),
1 => array(
'id' => '2',
'parent_id' => '1',
'name' => 'B',
),
2 => array(
'id' => '3',
'parent_id' => '1',
'name' => 'C',
)
);

$link=mysql_connect('127.0.0.1', 'root', '' ) or die( mysql_error() );//
mysql_select_db( 'class_db' );
$sql="SELECT * FROM treeview_items ORDER BY parent_id ";
$result=mysql_query( $sql );
$sq_data=array();
while($row=mysql_fetch_assoc( $result)){
$sq_data[]=array('id'=>$row['id'],'name'=>$row['name'],'parent_id'=>$row['parent_id']);

}


// reorder array
$menu = array();
foreach ( $sq_data as $item ) {
$menu[$item['parent_id']][] = $item;
}

// print menu
function makeMenu($menu,$parent_id,$dep) {

$html .= "\n";
$html .=str_repeat("\t", $dep);
$html .= "<ul>\n";
foreach ( $menu[$parent_id] as $item ) {
$html .= "<li id='tree_{$item['id']}'>{$item['name']}";
if ( isset($menu[$item['id']]) ) {
$html .= makeMenu($menu, $item['id'],$dep);
$dep++;
}
$html .= "\n\t</li>\n";
}
$html .= "</ul>\n";
return $html;
}
echo makeMenu($menu, 0,0);

?>

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 kinomelma 的頭像
    kinomelma

    基尼而絲(G.N.A.S)的大世界

    kinomelma 發表在 痞客邦 留言(0) 人氣()