一般来说实现无限极分类都是使用递归或者迭代的方式,小伙伴们看下本文的实现方式吧。
1,数据库设计:
2,代码:
代码如下:
PHP无限极分类 */ $cn = @R_502_198@_connect('localhost','root','') or die(@R_502_198@_error()); @R_502_198@_select_db('t',$cn) or die(@R_502_198@_error()); @R_502_198@_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 = @R_502_198@_query($sql); while ( ($row = @R_502_198@_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 = ''; } /** * 从子类开始逐级向上获取其父类 * @param number $cid * @param array $category * @return array: */ function getCategory($cid,&$category = array()) { $sql = 'SELECT * FROM category WHERE id='.$cid.' LIMIT 1'; $result = @R_502_198@_query($sql); $row = @R_502_198@_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 .= '>'; } return substr($str,strlen($str) - 1); } echo displayLists(0,3); echo displayCategory(13);
3,效果图:
是不是很简单呢,小伙伴们可以直接拿去用哈,不收版权费^_^
原文链接:https://www.f2er.com/php/23292.html