search
HomeBackend DevelopmentPHP TutorialPHP infinite classification and sorting method using recursion

As for functions such as adding and deleting, I won’t write much about them! If you look carefully, you will know how to use them. The difficulty is the display I hope the experts can expand it! This is the class

The code is as follows:

<?php 
/*======================================================== 
类名:catalog 
功能:无限分级类 
方法: 
树形显示分类 
catalog_show($id) //参数$id 递归调用 
流程:找到父分类为0所有根分类-> 一直递归取得所有分类并显示   
添加分类 
catalog_add($uid,$name) //$uid 父id //$name 分类名   
流程:依据$uid,在此id下添加一个新子id 
删除分类 
catalog_del($uid)//参数 $uid 数要删除的分类 
修改分类 
catalog_set($id,$name) //参数 $id 要修改的分类 //参数 $name 新的分类名 
变量: 
$config //数据库信息-> host,user,pass,dbname 
$catalog_dbname //分类数据库名 
数据库: 
catalog_id //分类的自然序号 
catalog_uid //分类的父分类 
catalog_name //分类名 
catalog_path_number //亲缘树数字形式 0:1:2 
catalog_path_char //亲缘树字符形式 分类1:分类1.1:分类1.1.1 
========================================================*/ 
class catalog{ 
var $config; 
var $catalog_dbname; 
var $links; 
private function connect(){ 
$this->links = mysql_connect($this->config[&#39;host&#39;],$this->config[&#39;user&#39;],$this->config[&#39;pass&#39;]) or die("错误: 第".LINE."行<br>".mysql_error()); 
mysql_select_db($this->config[&#39;dbname&#39;],$this->links); 
mysql_query("SET NAMES gb2312"); 
} 
function catalog_show($uid = 0){ 
$this->connect(); 
$sql = "Select * FROM ".$this->catalog_dbname. " 
Where catalog_uid = ". $uid ." 
orDER BY catalog_id "; 
$result = mysql_query($sql,$this->links) or die("错误: 第".LINE."行<br>".mysql_error()); 
if(mysql_num_rows($result) > 0){ 
while ($row = mysql_fetch_assoc($result)){   
if($this->sun_catalog($row[&#39;catalog_id&#39;])){//判断有没有子分类 
$cata_img = "<img  id = &#39;img".$row[&#39;catalog_id&#39;]."&#39; src=&#39;./img/last_node.jpg&#39; ōnclick=&#39;click_catalog(".$row[&#39;catalog_id&#39;].")&#39;/ alt="PHP infinite classification and sorting method using recursion" >"; 
}else{ 
$cata_img = "<img  src=&#39;./img/sp.jpg&#39;/ alt="PHP infinite classification and sorting method using recursion" >"; 
} 
$path = explode(":",$row[&#39;catalog_path_number&#39;]); 
if(count($path) > 1){ 
for($i=1;$i<count($path);$i++){ 
$path_img .= "<img  src=&#39;./img/sp.jpg&#39;/ alt="PHP infinite classification and sorting method using recursion" >"; 
} 
} 
echo $path_img.$cata_img; 
echo "<a class=&#39;menu&#39; href = &#39;javascrīpt:send_id(".$row[&#39;catalog_id&#39;].")&#39;>"; 
echo $row[&#39;catalog_name&#39;]."</a><br>"; 
$path_img = ""; 
if($this->sun_catalog($row[&#39;catalog_id&#39;])){   
$hidden_p = "style=&#39;display:none&#39;";   
echo "<p id = &#39;p".$row[&#39;catalog_id&#39;]."&#39; ".$hidden_p.">";   
$this->catalog_show($row[&#39;catalog_id&#39;]); 
echo "</p>"; 
}   
} 
}   
} 
private function sun_catalog($uid){//判断是否有子分类 
$sql = "Select * FROM ".$this->catalog_dbname. " 
Where catalog_uid = ". $uid ." 
orDER BY catalog_id "; 
$result = mysql_query($sql,$this->links) or die("错误: 第".LINE."行<br>".mysql_error()); 
if(mysql_num_rows($result) > 0){ 
return true; 
}else{ 
return false; 
} 
} 
function catalog_add($uid,$name){ 
//获取父id的亲缘树 
$this->connect(); 
$sql = "Select * FROM ".$this->catalog_dbname." 
Where catalog_id = &#39;".$uid."&#39;"; 
$result = mysql_query($sql,$this->links) 
or die("错误: 第".LINE."行<br>".mysql_error()); 
$row = mysql_fetch_assoc($result); 
$fid_path_number = $row[&#39;catalog_path_number&#39;];//id的数字亲缘树 
$fid_path_char = $row[&#39;catalog_path_char&#39;];//id的字符亲缘树 
//插入数据 先插入行->再找到最新插入的id, 在依据这个id进行修改 
$sql = "Insert INTO ".$this->catalog_dbname."(catalog_uid,catalog_name) 
VALUES(".$uid.",&#39;".$name."&#39;)"; 
$result = mysql_query($sql,$this->links) 
or die("错误: 第".LINE."行<br>".mysql_error()); 
$catalog_id = mysql_insert_id();//获取自己的id 
$catalog_path_number = $fid_path_number.":".$catalog_id;//得到自己的数字亲缘数 
$catalog_path_char = $fid_path_char.":".$name;//得到自己的字符亲缘数 
$sql = "Update &#39;".$this->catalog_dbname."&#39; 
SET 
catalog_path_number = &#39;".$catalog_path_number."&#39;, 
catalog_path_char = &#39;".$catalog_path_char."&#39; 
Where 
catalog_id = ".$catalog_id;   
mysql_query($sql,$this->links) 
or die("错误: 第".LINE."行<br>".mysql_error());   
} 
function catalog_del($id){ 
$this->connect(); 
$sql = "Delete FROM ".$this->catalog_dbname." 
Where catalog_id = ".$id; 
mysql_query($sql,$this->links) 
or die("错误: 第".LINE."行<br>".mysql_error()); 
} 
function catalog_set($id,$name){ 
$this->connect(); 
$sql = "Update ".$this->catalog_dbname." 
SET 
catalog_name = &#39;".$name."&#39; 
Where 
catalog_id = ".$id;   
mysql_query($sql,$this->links) 
or die("错误: 第".LINE."行<br>".mysql_error()); 
} 
} 
?>

The following mainly introduces the implementation method of infinite recursive classification and sorting in PHP. It is a very practical technique to realize infinite recursive classification and sorting through a simple recursive function. Friends in need can refer to

function order ($array,$pid=0){
    $arr = array();
        
    foreach($array as $v){
        if($v[&#39;pid&#39;]==$pid){
            $arr[] = $v;
            $arr = array_merge($arr,order($array,$v[&#39;id&#39;]));
        }
    }
    return $arr;
}

The above is the detailed content of PHP infinite classification and sorting method using recursion. For more information, please follow other related articles on the PHP Chinese website!

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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.