Home > Backend Development > PHP Tutorial > PHP unlimited classification example program_PHP tutorial

PHP unlimited classification example program_PHP tutorial

WBOY
Release: 2016-07-20 11:11:40
Original
748 people have browsed it

The principle of infinite classification: Just like creating a new folder under Windows, you can create a new folder under the newly created folder, and this will continue in an infinite loop. The same is true for infinite classification. The parent class can be divided into subclasses, and the subclasses can be divided into subclasses. Separate its subclasses and continue in an infinite loop

Example 1

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

$yArr    = array(
     1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),
     2 => array('id'=>'2','parentid'=>0,'name'=>'一级栏目二'),
     3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),
     4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),
     5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三'),
     6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),
     7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二'),
     8 => array('id'=>'8','parentid'=>2,'name'=>'二级栏目三'),
 );
 
 /**
  * 获取当前id的子ID
  * @param array $data 原始数组
  * @param int $id 当前id
  * @param int $layer 当前层级
  */
 function genCate($data, $pid = 0, $level = 0)
 {
     if($level == 10) break;
     $l        = str_repeat(" ", $level);
     $l        = $l.'└';
     static $arrcat    = array();
     $arrcat    = empty($level) ? array() : $arrcat;
     foreach($data as $k => $row)
     {
         /**
          * 如果父ID为当前传入的id
          */
         if($row['parentid'] == $pid)
         {
             //如果当前遍历的id不为空
             $row['name']    = $l.$row['name'];
             $row['level']    = $level;
             $arrcat[]    = $row;
             //var_array($arr);
             genCate($data, $psiff, $row['id'], $level+1);//递归调用
         }
     }
     return $arrcat;
 }
 
 $carr    = genCate($yArr);
 echo "";

$yArr = 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'),
4 => array('id'=>'4','parentid'=>1,'name'=>'Second-level column two'),
5 => array('id'=>'5','parentid'=>2,'name'=>'Second-level column three'),
6 => array('id'=>'6','parentid'=>3,'name'=>'Third-level column one'),
7 => array('id'=> '7','parentid'=>3,'name'=>'Third-level column two'),
8 => array('id'=>'8','parentid'= >2,'name'=>'Second-level column three'),
);

/**
* Get the sub-ID of the current id
* @param array $data original array
* @param int $id current id
* @param int $layer current level
>*/
function genCate($data, $pid = 0, $level = 0)
{
if($level == 10) break;
$l = str_repeat("    ", $ level);
$l = $l.'└';
static $arrcat = array();
$arrcat = empty($level) ? array() : $arrcat; foreach ($ data as $ k = & gt; $ row)
{
/**
          * If the parent ID is the currently passed in id
          * /
if ($ row ['paintid'] == $ pid )
                                                                                                       'level'] = $level;
$arrcat[] = $row;
], $level+1);//Recursive call
                                                                                                                                                           );
echo "";

Note: Because it is an infinite call, I added a judgment to let it jump out when the level $level=10. No normal website would have more than 10 levels of

directory structure.

After executing the static variable, determine the current level. If the level is 0, it means that this is the highest level menu. You need to clear the $arrcate data and re-declare it


Example 2

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

//我们建一个表"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=InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;

//We create a table "class"

CREATE TABLE `class` (

`id` int(11) NOT NULL auto_increment COMMENT 'classification id',
 代码如下 复制代码

< ?php

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']."< br>"; //这样就把每个大类循环出来了。

}

//同样我们可以把新闻的子类循环出来。

$result=$db->query("select * from class where f_id=1"); 
//查找f_id=1的分类,也就是查找‘新闻’的子类。

while($row=$result->fetch_assoc()){

echo $row['name']."

"; //这样就把‘新闻’的子类循环出来了。注意:只是子类,不包括孙子类。

}

` f_id` int(11) NOT NULL COMMENT 'parent id',`name` varchar(25) collate gbk_bin NOT NULL COMMENT 'category name',PRIMARY KEY (`id`)) ENGINE= InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;
Code
The code is as follows Copy code
< ?php <🎜><🎜 >header("Content-type:text/html;charset=utf-8"); <🎜><🎜>$db=new mysqli("localhost","root","","news_php100") ; <🎜 >//Instantiate a database connection. Before using this, be sure to load the mysqli class library, <🎜> or use mysql_connect to connect. <🎜><🎜>if(mysqli_connect_errno()){<🎜><🎜>echo "Link failed:".mysqli_connect_error();<🎜><🎜>exit(); } <🎜><🎜>$db- >query("set names utf8");$result=$db->query("select name from class where f_id=0"); //Find the category of f_id=0 , that is, search for each major category. while($row=$result->fetch_assoc()){echo $row['name']."< br>"; //This way, each The major categories are cycled out. }//Similarly we can loop out the subcategories of news. $result=$db->query("select * from class where f_id=1"); //Find the category of f_id=1, that is, find the subcategory of 'news'. while($row=$result->fetch_assoc()){echo $row['name'].""; //This will The subcategory of 'News' is cycled out. Note: only subcategories, excluding grandchild categories. }

//Writing here, we will find a problem. If this classification is a 10-level classification, do we have to write
10 loops to cycle out each of its subcategories? If there are more levels of classification, it is obviously unrealistic to write like this.

//Then what’s the solution? We can write a recursive function, passing in f_id as a parameter, and

continuously looping through each f_id value, that is to say, looping out the subclasses of each f_id value.

//First we save the values ​​of each category in a two-dimensional array, which is useful in the following recursive function.

table>

?>

Example 3

php unlimited classification, supports output tree diagram

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

$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< count($arr);$i++){ //对每个分类进行循环。

if($arr[$i][1]==$f_id){ //$arr[$i][1]表示第$i+1个分类的f_id的值。
开始$f_id=0,也就是把f_id=0的分类输出来。

echo $arr[$i][2]."< br>"; //$arr[$i][1]表示第$i+1个分类的name的值。

fenlei($arr[$i][0]); //$arr[$i][1]表示第$i+1个分类的id的值。进行递归
,也就是把自己的id作为f_id参数把自己的子类再循环出来。

}

}

}

fenlei(); //使用这个函数.

$result=$db->query("select * from class");while($row=$result->fetch_assoc()){$arr[]=array($row[id],$row[f_id],$row[name]); //Each row saves the information of id, f_id, name of a category. }function fenlei($f_id=0){ //$f_id is initialized to 0, that is, the cycle starts from the largest category.global $arr; // Only by declaring $arr as a global variable can it be referenced in the function. for($i=0;$i< count($arr);$i++){ //Loop for each category. if($arr[$i][1]==$f_id){ //$arr[$i][1] represents the value of f_id of the $i+1th category. Start with $f_id=0, that is, output the classification of f_id=0. echo $arr[$i][2]."< br>"; //$arr[$i][1] represents the value of the name of the $i+1th category. fenlei($arr[$i][0]); //$arr[$i][1] represents the value of the id of the $i+1th category. Perform recursion , that is, use your own id as the f_id parameter to recycle your own subclasses. }}}fenlei(); //Use this function.
The code is as follows Copy Code

/**
* Universal tree class that can generate any tree structure
*/
class tree
{
/**
* 2-dimensional array required to generate tree structure
* @var array
* /
var $arr = array();

/**
* Modification symbols required to generate a tree structure, which can be replaced by images
* @var array
*/
var $icon = array('│','├','└');

/**
 * @access private
 */
var $ret = '';

/**
* Constructor, initialize class
* @param array 2-dimensional array, for example:
* 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 1'),
* 4 => array('id'=>'4','parentid'=>1,'name'=>'Second-level column two'),
* 5 => array('id'=>'5','parentid'=>2,'name'=>'Second-level column three'),
* 6 => array('id '=>'6','parentid'=>3,'name'=>'Third-level column one'),
* 7 => array('id'=>'7', 'parentid'=>3,'name'=>'Third-level column two')
* )
*/
function tree($arr=array())
{
$this->arr = $arr;
$this->ret = '';
return is_array($arr);
}

/ **
* Get the parent array
* @param int
* @return array
*/
function get_parent($myid)
{
$newarr = array();
if(!isset($this->arr[$myid])) return false;
$pid = $this->arr[$myid]['parentid'];
$pid = $this->arr[$pid]['parentid'];
if(is_array($this->arr))
{
foreach($this->arr as $id => $a)
{
if($a['parentid '] == $pid) $newarr[$id] = $a;
}
}
return $newarr;
}

/**
* Get the child array
* @param int
* @return array
*/
function get_child($myid)
{
$a = $newarr = array();
if(is_array($this->arr))
{
foreach( $this->arr as $id => $a)
{
if($a['parentid'] == $myid) $newarr[$id] = $a;
}
}
return $newarr ? $newarr : false;
}

/**
* Get the current position array
* @param int
* @return array
*/
function get_pos($myid,&$newarr)
{
$a = array();
if(!isset($this->arr[$myid])) return false;
$newarr[] = $this->arr[$ myid];
$pid = $this->arr[$myid]['parentid'];
if(isset($this->arr[$pid]))
{
$this->get_pos($pid,$newarr);
}
if(is_array($newarr))
{
krsort($newarr);
foreach($newarr as $v)
{
$a[$v['id']] = $v;
}
}
return $a;
}


/**
* -------------------------------------
* Get tree structure
* ---------------------------------------------
* @author Midnight(Yang Yunzhou), yangyunzhou@foxmail.com
* @param $myid means to get all the children under this ID
* @param $str Generate basic code of tree structure, for example: "< option value=$id

$select>$spacer$name"
* @param $sid The selected ID, such as when making a tree drop-down box.
* @param $adds
* @param $str_group
* @return unknown_type
*/
function get_tree($myid, $str, $sid = 0, $adds = '', $str_group = '')
{
$number=1;
$child = $this->get_child($myid);
if(is_array($child))
{
$total = count($ child);
foreach($child as $id=>$a)
{
$j=$k='';
if($number==$total)
{
$j .= $this->icon[2];
}
else
{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';
$selected = $id= =$sid ? 'selected' : '';
@extract($a);
$parentid == 0 && $str_group ? eval("$nstr = "$str_group";") : eval

("$nstr = "$str";");
$this->ret .= $nstr;
$this->get_tree($id, $str, $sid, $adds.$k.' ',$str_group);
$number++;
}
}
return $this->ret;
}
/**
* Similar to the previous method, but allows multiple selections
*/
function get_tree_multi($myid, $str, $sid = 0, $adds = '')
{
$number=1;
$child = $this-> ;get_child($myid);
if(is_array($child))
{
$total = count($child);
foreach($child as $id=>$a)
{
$j=$k='';
if($number==$total)
{
$j .= $this->icon[2];
}
else
{
$j .= $this->icon[1];
$k = $adds ? $this->icon[0] : '';
}
$spacer = $adds ? $adds.$j : '';

$selected = $this->have($sid,$id) ? 'selected' : ' ';
//echo $sid.'=>'.$id.' : '.$selected.' .
';
@extract($a);
eval("$nstr = "$str";");
$this->ret .= $nstr;
$this->get_tree_multi($id, $str, $sid, $adds. $k.' ');
$number++;
}
}
return $this->ret;
}

function have($list, $item){
return(strpos(',,'.$list.',',','.$item.','));
}
}
?>

Note: There is no platform restriction, you only need to tell the id, parentid, name
The three unlimited classification codes summarized above have no platform restrictions, but only It can be used in php. We only need to understand the relationship between id, parentid and name.


http://www.bkjia.com/PHPjc/444632.html

truehttp: //www.bkjia.com/PHPjc/444632.htmlTechArticleThe principle of unlimited classification: just like creating a new folder under windows, you can create a new one under the new folder Folders, this loop continues indefinitely, and the same goes for infinite categories. The parent class can...
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