宝马娱乐在线112222 > 网络应用 > php中无限级分类程序代码

原标题:php中无限级分类程序代码

浏览次数:110 时间:2019-10-01

无限分类就像windows下新建一个文件夹,在新建的文件夹下又可以新建一个文件夹,这样无限循环下去,无限分类也是这样,父类可以分出它子类,子类又可以分出它的子类,这样一直无限循环下去

创建数据库教程以及表:

图片 1 

CREATE DATABASE `sortclass`DEFAULT CHARSET utf8;
CREATE TABLE IF NOT EXISTS `class` (
`cid` mediumint(8) unsigned NOT NULL auto_increment,
`pid` mediumint(8) unsigned NOT NULL,
`cname` varchar(50) NOT NULL,
PRIMARY KEY (`cid`),
KEY `pid` (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

 代码如下

处理文件示例:

--

<?php
header("Content-type: text/html; charset=utf-8");
//连接数据库
$link = mysql教程_connect('localhost','root','eric') or die(mysql_error());
mysql_select_db('sortclass',$link);
//无限分类类库
class SortClass{

-- 数据库: `tree`

CREATE DATABASE `tree` DEFAULT CHARACTER SET gb2312 COLLATE gb2312_chinese_ci;
USE `tree`;

 

--

var $data = array();
var $child = array(-1=>array());
var $layer = array(-1=>-1);
var $parent = array();
var $link;
var $table;
function SortClass($link, $table){
$this->setNode(0, -1, '顶极节点');
$this->link = $link;
$this->table = $table;
$node = array();
$results = mysql_query('select * from '.$this->table.'',$this->link);
while($node = mysql_fetch_assoc($results)){
$this->setNode($node['cid'],$node['pid'],$node['cname']);
}
}
function setNode ($id, $parent, $value){
$parent = $parent?$parent:0;
$this->data[$id] = $value;
$this->child[$id] = array();
$this->child[$parent][] = $id;
$this->parent[$id] = $parent;
$this->layer[$id] = !isset($this->layer[$parent])? 0 : $this->layer[$parent] + 1;
}
function getList (&$tree, $root= 0){
foreach ($this->child[$root] as $key=>$id){
$tree[] = $id;
if ($this->child[$id]) $this->getList($tree, $id);
}
}
function getValue ($id){return $this->data[$id];}
function getLayer ($id, $space = false){
return $space?str_repeat($space, $this->layer[$id]):$this->layer[$id];
}
function getParent ($id){return $this->parent[$id];}
function getParents ($id){
while ($this->parent[$id] != -1){
$id = $parent[$this->layer[$id]] = $this->parent[$id];
}
ksort($parent);
reset($parent);
return $parent;
}
function getChild ($id){return $this->child[$id];}
function getChilds ($id = 0){
$child = array($id);
$this->getList($child, $id);
return $child;
}
function addNode($name,$pid){
mysql_query("insert into $this->table (`pid`,`cname`) values ('$pid','$name')",$this->link);
}
function modNode($cid, $newName){
mysql_query("update $this->table set `cname`='$newName' where `cid` = $cid",$this->link);
}
function delNode($cid){
$allChilds = $this->getChilds($cid);
$sql ='';
if(empty($allChilds)){
$sql = "delete from $this->table where `cid` = $cid";
}else{
$sql = 'delete from '.$this->table.' where `cid` in ('.implode(',',$allChilds).','.$cid.')';
}
mysql_query($sql,$this->link);
}
function moveNode($cid, $topid){
mysql_query("update $this->table set `pid`=$topid where `cid` = $cid", $this->link);
}
}
//函数
function back(){
echo '<script language="javascript教程">window.location.href="test.php?"+new Date().getTime();</script>';
exit;
}
//声成select
function makeSelect($array,$formName){
global $tree;
$select = '<select name="'.$formName.'">';
foreach ($array as $id){
$select.='<option value="'.$id.'">'.$tree->getLayer($id, '|-').$tree->getValue($id)."</option>";
}
return $select.'</select>';
}
$tree = new SortClass($link,'`class`');
$op = !empty($_POST['op']) ? $_POST['op'] : $_GET['op'];
if(!empty($op)){

-- 表的结构 `class`

 

CREATE TABLE `class` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(10) NOT NULL,
  `pid` int(11) NOT NULL,
  `depth` varchar(100) default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=gb2312 AUTO_INCREMENT=30 ;  

<?php
$link =mysql_connect('localhost','root','root');
mysql_select_db('tree');
mysql_query ( 'set names GBK' );
if($_GET['act']=='add'){
   $name=$_POST['name'];
   if($name=='') exit('name not null');
      $pid=$_POST['pid'];
          if($pid !=0){
             $sql="select * from class where id=".$pid;
             $result =mysql_query($sql);
             $row = mysql_fetch_array($result);
             $depth=$row['depth'].','.mysql_insert_id();//$getID即为最后一条记录的ID
          }else{
             $depth=0;
       }
    $sql="INSERT INTO class(name,pid,depth) VALUES('".$name."','".$pid."','".$depth."')";
    $result =mysql_query($sql);
       if(!$result){
          exit("shibai $sql");
       }else{
          exit("chenggong");
    }
}
?>
<form id="form1" name="form1" method="post" action="?act=add">
  <table width="327" border="1" cellpadding="0" cellspacing="0">
    <tr>
      <td width="97" height="27">名称</td>
      <td width="224"><label for="name"></label>
      <input type="text" name="name" id="name" /></td>
    </tr>
    <tr>
      <td height="30">栏目</td>
      <td><select name="pid" id="pid">
            <option value="0">-----顶级分类-----</option>
            <?php
             sort_s(0);
   ?>
      </select></td>
    </tr>
    <tr>
      <td height="35"> </td>
      <td><input type="submit" name="button" id="button" value="提交" /></td>
    </tr>
  </table>
</form>
<br />
<br />
<br />
<br />

<?php
//$sql = "select * from `class` order by sort asc, id Desc";
//$sql="select * from class where pid=0";
//$result =mysql_query($sql);
 //while($row = mysql_fetch_array($result)){
  //$class_arr[] = array($row['id'],$row['name'],$row['classid'],$row['sort']);
    // echo $row['name'].$row['id'].'---'.$row['pid'].'<br>';
        sorttree(0);
 
  
 //}
 
function sorttree($id){
 //if()
 $sql="select * from class where pid=".$id;
    $result =mysql_query($sql);
 //$a=mysql_fetch_array($result);
 //$row = mysql_fetch_array($result);
 while($row = mysql_fetch_array($result)){
    $rid=explode(",",$row['depth']);
    $i=count($rid);
    $n = str_pad('',$i,'-',STR_PAD_RIGHT);
    $n = str_replace("-","    ",$n);
 //print_r($row).'<br>';
    if($row['pid']==0){
       echo $n.'|-----'.$row['name'].'-----|<br>';
    }else{
       echo $n.'    <font color="#FF0000">|-</font>'.$row['name'].'<br>';
       }
    sorttree($row['id']);
 }
}

function sort_s($id){
 //if()
 $sql="select * from class where pid=".$id;
    $result =mysql_query($sql);
 //$a=mysql_fetch_array($result);
 //$row = mysql_fetch_array($result);
 while($row = mysql_fetch_array($result)){
    $rid=explode(",",$row['depth']);
    $i=count($rid);
    $n = str_pad('',$i,'-',STR_PAD_RIGHT);
    $n = str_replace("-","    ",$n);
 //print_r($row).'<br>';
    if($row['pid']==0){
        echo "<option value="".$row['id']."" style='background:#ccc' >".$n.'|------'.$row['name']."-----|</option>rn";
    }else{
        echo "<option value="".$row['id']."">".$n.'    |- '.$row['name']."</option>rn";
    }
    sort_s($row['id']);
 }
}
?>

图片 2

总结原理

如何把它的各个分类一一列出来呢?
首先我们假设有这样的一个三级分类,新闻→PHP新闻→PHP6.0出来了。
如果我们要查找“PHP6.0出来了”这条新闻,我们先点击新闻,然后再点击PHP新闻

就可以查出来了,也就是说我们可以通过祖父类一级一级地往下找,反过来我们只要

知道一个子类的父类,就可以把它查找出来了。这样我们在设计数据库时就可以多设

计一个父类id的字段就可以实现无限分类的功能了

if($op=='add'){
$tree->addNode($_POST['cname'],$_POST['pid']);
back();
}

if($op=='mod'){
$tree->modNode($_POST['cid'],$_POST['cname']);
back();
}

if($op=='del'){
$tree->delNode($_GET['cid']);
back();
}

if($op=='move'){
$tree->moveNode($_POST['who'],$_POST['to']);
back();
}
}
$category = $tree->getChilds();
?>
<style type="text/css教程">
body{font-size:12px;}
ul{list-style:none;}
a{cursor:pointer;}
</style>
<script language="javascript">
function $(e){return document.getElementById(e);}
function mod(cid){
$('cid').value=cid;
$('op').value='mod';
$('name').style.border='1px solid red';
}
</script>
<form action="test.php" method="post">
名称:<input type="text" id="name" name="cname" /> 添加到:<?=makeSelect($category,'pid')?><br />
<input type="hidden" id="op" name="op" value="add" />
<input type="hidden" id="cid" name="cid" />
<input type="submit" value="Submit" />
</form>
<h3>移动分类</h3>
<form action="test.php" method="post">
<?=makeSelect($category,'who')?>移动到:<?=makeSelect($category,'to')?>
<input type="hidden" id="op" name="op" value="move" />
<input type="submit" value="Submit" />
</form>
<ul>
<?php
foreach ($category as $id){
echo '<li>'.$tree->getLayer($id, '|- ').$tree->getValue($id).' <a href="test.php?op=del&cid='.$id.'">Del</a> <a onclick="mod('.$id.')">Edit</a> </li>';
}
?>
</ul>

简单的通过递归查询加目录path字段的无限分类
缺点:查询数据库次数太多,不方便其他操作,比如删除节点。添加节点,移动节点
2,左右值无限分类,预排序二叉树
缺点:操作繁琐,数据库冗余,且添加删除修改都要进行左右值更新

用递归无无限分页类的枋心算法

本文由宝马娱乐在线112222发布于网络应用,转载请注明出处:php中无限级分类程序代码

关键词:

上一篇:宝马娱乐在线:php file_get_contents获取百度热词代

下一篇:php 表单令牌防止重复提交原理