温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在php中使用mysql实现一个无限级分类

发布时间:2021-01-27 16:01:04 来源:亿速云 阅读:159 作者:Leah 栏目:开发技术

怎么在php中使用mysql实现一个无限级分类?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

数据库字段大概如下:

复制代码 代码如下:

id 编号
fid 父分类编号
class_name 分类名
path 分类路径,以 id 为节点,组成类似 ,1,2,3,4, 这样的字符串

可以假设有如下的数据:

复制代码 代码如下:


id fid class_name path
1  0       分类1 ,       1,
2  0       分类2 ,       2,
3  1       分类1-1 ,    1,3,
4  1       分类1-2 ,    1,4,
5  2       分类2-1 ,    2,5,
6  4       分类1-2-1 , 1,4,6,

无限级分类操作代码:

<?php   
$sql=”SELECT * FROM tree order by path”;  
$result=$nbs->Query($sql);  
while($rows=$nbs->fetch_array($result)){  
  if(substr_count($rows['path'],',')>2){  
    for($i=0;$i<(substr_count($rows['path'],',')-2);$i++)  
      echo ‘ ‘;  
  }  
  echo $rows['class_name'].'<br>';  
}  
?>  

$conn = mysql_connect ( 'localhost', 'root', 'root' );
mysql_select_db ( 'wanggou123', $conn );
mysql_query ( 'set names UTF8' );
$sql = "select id,concat(catpath,'-',id) as abspath,name from category order by abspath";
 
$query = mysql_query ( $sql );
while ( $row=mysql_fetch_array($query)) {
  /**
  * 第一种展示方法
*/
/*$space = str_repeat ( '&nbsp;&nbsp;&nbsp;&nbsp;', count ( explode ( '-', $row ['abspath'] ) ) - 1 );
echo $space . $row ['name'] . '
';*/
/**
 第二种展示方法
*/
$space = str_repeat ( '——', count ( explode ( '-', $row ['abspath'] ) ) - 1 );
$option .= '' . $space . $row ['name'] . '<Br>';
}
echo $option;
exit();
echo '<select name="opt">' . $option . '</select>';

看完上述内容,你们掌握怎么在php中使用mysql实现一个无限级分类的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI