PHP實現無限極分類圖文教程,
一般來說實現無限極分類都是使用遞歸或者迭代的方式,小伙伴們看下本文的實現方式吧。
1,數據庫設計:
2,代碼:
復制代碼 代碼如下:/**
* @author koma
* @todo PHP無限極分類
*/ $cn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('t', $cn) or die(mysql_error());
mysql_query('set names utf8');
/**
* 從頂層逐級向下獲取子類
* @param number $pid
* @param array $lists
* @param number $deep
* @return array
*/ function getLists($pid = 0, &$lists = array(), $deep = 1) {
$sql = 'SELECT * FROM category WHERE pid='.$pid;
$res = mysql_query($sql);
while ( ($row = mysql_fetch_assoc($res)) !== FALSE ) {
$row['catename'] = str_repeat(' ', $deep).'|---'.$row['catename'];
$lists[] = $row;
getLists($row['id'], $lists, ++$deep); //進入子類之前深度+1 --$deep; //從子類退出之後深度-1 }
return $lists;
}
function displayLists($pid = 0, $selectid = 1) {
$result = getLists($pid);
$str = '<select>';
foreach ( $result as $item ) {
$selected = "";
if ( $selectid == $item['id'] ) {
$selected = 'selected';
}
$str .= '<option '.$selected.'>'.$item['catename'].'</option>';
}
return $str .= '</select>';
} /**
* 從子類開始逐級向上獲取其父類
* @param number $cid
* @param array $category
* @return array:
*/ function getCategory($cid, &$category = array()) {
$sql = 'SELECT * FROM category WHERE id='.$cid.' LIMIT 1';
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ( $row ) {
$category[] = $row;
getCategory($row['pid'], $category);
}
krsort($category); //逆序,達到從父類到子類的效果 return $category;
}
function displayCategory($cid) {
$result = getCategory($cid);
$str = "";
foreach ( $result as $item ) {
$str .= '<a href="'.$item['id'].'">'.$item['catename'].'</a>>';
}
return substr($str, 0, strlen($str) - 1);
}
echo displayLists(0, 3);
echo displayCategory(13);
3,效果圖:
是不是很簡單呢,小伙伴們可以直接拿去用哈,不收版權費^_^