search
HomeBackend DevelopmentPHP TutorialPHP unlimited classification example program_PHP tutorial

PHP unlimited classification example program_PHP tutorial

Jul 20, 2016 am 11:11 AM
phpwindowsDownClassificationprincipleCanexistExamplefolderNewunlimitedofprogram

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',
 代码如下 复制代码

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']."

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

}

` 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
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'].""; //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

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参数把自己的子类再循环出来。

}

}

}

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;$iif($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].""; //$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: "

$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...
Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.