PHP infinite classification implementation program_PHP tutorial

WBOY
Release: 2016-07-20 11:11:24
Original
853 people have browsed it

1. The database performs unique indexing by setting the parent class ID, and then uses recursive calls of functions to achieve infinite classification; 2. The database design is arranged in a specific format, and then uses mysql to query the key function: concat. The program implementation is relatively simple

First, we assume that there is such a three-level classification, News → PHP News → PHP6.0 is out.
If we want to find the news "PHP6.0 is out", we first click on the news, and then click on the PHP news

to find out, that is to say, we can use the grandfather class level Searching down one level, conversely, as long as we

know the parent class of a subclass, we can find it. In this way, when designing the database, we can set an additional field of

to calculate a parent class ID to achieve unlimited classification.

The code is as follows Copy code
//We create a table "class"
 代码如下 复制代码
//我们建一个表"class"
CREATE TABLE `class` (
  `id` int(11) NOT NULL auto_increment COMMENT '分类id',
  `f_id` int(11) NOT NULL COMMENT '父id',
  `name` varchar(25) collate gbk_bin NOT NULL COMMENT '分类名称',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;
CREATE TABLE `class` ( `id` int(11) NOT NULL auto_increment COMMENT 'classification id', `f_id` int(11) NOT NULL COMMENT 'parent id', `name` varchar(25) collate gbk_bin NOT NULL COMMENT 'category name', PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;


//First, we insert the "News" category into the database. Because "News" is the largest category and there is no parent category on it, so I set its f_id to 0.
INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(1, 0, 'News'); //The id field grows automatically and no value is required.

//Then we insert the category 'PHP News' into the database. The id of its parent category 'News' is 1, so its f_id is set to 1.
INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(2, 1, 'PHP News');

//Then we insert 'PHP6 into the database .0 came out' of this category, the id of its parent category 'PHP News' is 2, so its f_id is set to 2.
INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(3, 2, 'PHP6.0 is out');

//Similarly, we can do this Inserting categories all the way down will reach infinite categories.
//We can find that the key to inserting a category is to find the id of the parent category of this category, and then use it as the value of the f_id field of this category.
//Suppose you want to insert the category 'Technology' at the same level as 'News', that is to say, it is also the largest category and there is no parent category above, then its f_id is also set to 0;
INSERT INTO ` class` (`id`, `f_id`, `name`) VALUES(4, 0, 'Technology');

//There is another category 'PHP Technology' under 'Technology', then we How to insert it? First find the id of the parent class 'Technology' of 'PHP Technology', and then use it as the value of your own f_id field.
INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(5, 4, 'PHP technology');

//After seeing this, everyone should understand How to insert each category into the database. No more examples.

We already know how to insert each category into the database, but how to list each category?

 代码如下 复制代码

header("Content-type:text/html;charset=utf-8");
$db=new mysqli("localhost","root","","news_php100") ; //实例化一个数据库连接。使用这个前一定要确保已经加载了mysqli类库,或者用mysql_connect这个方式连接。
if(mysqli_connect_errno()){
echo "链接失败:".mysqli_connect_error();
exit(); }
$db->query("set names utf8");
$result=$db->query("select name from class where f_id=0"); //查找f_id=0的分类,也就是查找每一个大类。
while($row=$result->fetch_assoc()){
      echo $row['name']."
";        //这样就把每个大类循环出来了。
}
//同样我们可以把新闻的子类循环出来。
$result=$db->query("select * from class where f_id=1"); //查找f_id=1的分类,也就是查找‘新闻’的子类。
while($row=$result->fetch_assoc()){
      echo $row['name']."
";        //这样就把‘新闻’的子类循环出来了。注意:只是子类,不包括孙子类。
}
//写到这里,我们会发现一个问题,如果这个分类是10级分类,难道我们要写10个循环把它每个子类循环出来?如果是更多级分类呢,这样写显然是不现实的。
//那又有什么办法解决呢?我们可以写一个递归的函数,把f_id作为参数传入,不断循环每一个f_id的值,也就是说把每一个f_id值的子类循环出来。
//首先我们把各个分类的值保存在一个二维数组中,在下面的递归函数里有用。
$result=$db->query("select * from class");
while($row=$result->fetch_assoc()){
     $arr[]=array($row[id],$row[f_id],$row[name]);    //每一行保存一个分类的id,f_id,name的信息。
}
function fenlei($f_id=0){     //$f_id初始化为0,也就是从最大分类开始循环.
    global $arr;   //声明$arr为全局变量才可在函数里引用。
    for($i=0;$i           if($arr[$i][1]==$f_id){         //$arr[$i][1]表示第$i+1个分类的f_id的值。开始$f_id=0,也就是把f_id=0的分类输出来。
                 echo $arr[$i][2]."
"; //$arr[$i][1]表示第$i+1个分类的name的值。
            fenlei($arr[$i][0]);   //$arr[$i][1]表示第$i+1个分类的id的值。进行递归,也就是把自己的id作为f_id参数把自己的子类再循环出来。
}
}
}
?>


The three fields id, parentid, and name
The algorithm is also very simple and recursive. It was silly when using recursion in the past. It should be said to be extremely silly, because in recursion, all the subclasses are obtained by querying the data table. , I recently got enlightened and thought of a method that everyone on earth can think of. The following is the code, a class

The code is as follows
 代码如下 复制代码

class Tree {

/**
* 从数据库查询出的所有分类信息
* @var array
*/
var $arr;
/**
* 如下格式
* var $arr = array(
1 => array(‘id’=>’1′,’parentid’=>0,’name’=>’一级栏目一’),
 2 => array(‘id’=>’2′,’parentid’=>0,’name’=>’一级栏目二’),
 3 => array(‘id’=>’3′,’parentid’=>1,’name’=>’二级栏目一’),
 );*/

 /**
  * 输出结构
  * @var array
  */
 var $tree = array();
 /**
  * 树形递归的深度
  * @var int
  */
 var $deep = 1;

 /**
  * 生成树形的修饰符号
  * @var array
  */
 var $icon = array(‘│’,'├’,'└’);
 /**
  * 生成指定id的下级树形结构
  * @param int $rootid 要获取树形结构的id
  * @param string $add 递归中使用的前缀
  * @param bool $parent_end 标识上级分类是否是最后一个
  */
 function getTree($rootid = 0,$add = ”,$parent_end =true){
  $is_top = 1;
  $child_arr = $this->getChild($rootid);
  if(is_array($child_arr)){
   $cnt = count($child_arr);
   foreach($child_arr as $key => $child){
    $cid = $child['id'];
    $child_child = $this->getChild($cid);
    if($this->deep >1){
     if($is_top == 1 && $this->deep > 1){
      $space = $this->icon[1];
      if(!$parent_end)
      $add .=  $this->icon[0];
      else $add .= ‘ ’;
     }

     if($is_top == $cnt){
      $space = $this->icon[2];
      $parent_end = true;
     }else {
      $space = $this->icon[1];
      $parent_end = false;
     }
    }
    $this->tree[] = array(‘spacer’=>$add.$k.$space,
           ‘name’=>$child['name'],
           ‘id’=>$cid
    );
    $is_top++;

    $this->deep++;
    if($this->getChild($cid))
    $this->getTree($cid,$add,$parent_end);
    $this->deep–;

   }

  }
  return $this->tree;
 }

 /**
  * 获取下级分类数组
  * @param int $root
  */
 function getChild($root = 0){

  $a = $child = array();
  foreach($this->arr as $id=>$a){
   if($a['parentid'] == $root){
    $child[$a['id']] = $a;
   }
  }
  return $child?$child:false;
  
 }
 /**
  * 设置源数组
  * @param $arr
  */
 function setArr($arr = array()){
  $this->arr = $arr;
 }
}

Copy code


class Tree {
/**<🎜> * All classification information queried from the database <🎜> * @var array<🎜>*/<🎜> var $arr;<🎜>/**<🎜> * The following format<🎜> * var $arr = array(<🎜> 1 => array('id'=>'1′,'parentid'=>0,'name'=>' First-level column one'), 2 => array('id'=>'2','parentid'=>0,'name'=>'First-level column two'), 3 => array('id'=>'3′,'parentid'=>1,'name'=>'Second-level column one'), );*/ /** * Output structure * @var array*/ var $tree = array( ); /** * Depth of tree recursion * @var int*/ var $deep = 1; /** * Generate tree-shaped modification symbols * @var array*/ var $icon = array('│',' ├','└'); /** * Generate a subordinate tree structure with the specified id * @param int $rootid To obtain the id of the tree structure * @param string $add The prefix used in recursion * @param bool $ parent_end identifies whether the parent category is the last */ function getTree($rootid = 0,$add = ”,$parent_end =true){ $is_top = 1; $child_arr = $this->getChild($rootid); if(is_array($child_arr)){ $cnt = count($child_arr); foreach($child_arr as $key => $child){ $cid = $child['id']; $child_child = $this->getChild($cid); if($this->deep > ;1){ if($is_top == 1 && $this->deep > 1){ $space = $this->icon[1]; if(!$parent_end ) $add .= $this->icon[0]; else $add .= '  '; } if($is_top == $ cnt){ $space = $this->icon[2]; $parent_end = true; }else { $space = $this->icon[1]; $parent_end = false; } } $this->tree[] = array('spacer'=>$add.$k.$space, 'name' =>$child['name'],         'id'=>$cid      );                                      ($this->getChild($cid)) $this->getTree($cid,$add,$parent_end); $this->deep–; } } return $this->tree; } /** * Get the lower-level classification array * @param int $root*/ function getChild($root = 0){ $a = $child = array(); foreach($this->arr as $id=>$a){ if($a['parentid'] == $ root){ $child[$a['id']] = $a; } } return $child?$child:false; } /** * Set the source array * @param $arr*/ function setArr($arr = array()){ $this->arr = $arr; }} Save the structure into an array through a query, and then perform recursive operations on the array, which undoubtedly greatly improves the running efficiency of the program It is very simple to use the code

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444660.htmlTechArticle1. The database performs unique indexing by setting the parent class ID, and then uses recursive calls of functions to achieve unlimited classification; 2 , the database design is arranged in a specific format, and then uses mysql to check...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template