Table of Contents
php implements infinite classification (recursive method), php recursion
Home Backend Development PHP Tutorial PHP implements infinite classification (recursive method), PHP recursion_PHP tutorial

PHP implements infinite classification (recursive method), PHP recursion_PHP tutorial

Jul 13, 2016 am 09:44 AM
php recursion

php implements infinite classification (recursive method), php recursion

I believe that many friends who learn php will try to build an online mall as a way to improve their skills. You should be comfortable with various operations on product classification, product names, etc., then you can try making unlimited classification lists.

Search the PHP Infinitus classification on the Internet. There are many, but many of them are the same. Moreover, the writing is very messy and there are a lot of codes. How do we learn? Those are not reliable, so we should tinker with Infinitus classification by ourselves. .

What is infinite classification?

Infinite-level classification is a classification technique. For example, department organization, article classification, subject classification, etc. often use infinite-level classification. It can be simply understood as classification. In fact, if we think about it carefully, there are simply too many classifications in life. Clothes can be divided into men's clothing and women's clothing, tops and pants, and they can also be classified according to age groups. Classification is everywhere, and classification appears "infinite". I won’t talk about the necessity of infinite classification here.

Introduction to the principle of infinite classification

Infinite classification may seem "high-end", but in fact the principle is very simple. Infinite classification not only requires the ingenuity of the code, but also relies on the rationality of the database design. To satisfy infinite classification, the database needs to have two necessary fields, id and pid. The id is used to identify itself, while the pid is used to indicate the parent id. In other words, each classification record not only describes itself, but also describes another ID that it is most closely concerned about. What seemed like a complicated matter was solved with such a little trick.

Without further ado, it’s time to show the examples of this article.

As an avid pirate fan, I will use the character organization of "One Piece" as an example in this article.

Database preparation:

 Build table onepiece:

create table onepiece(
  id int auto_increment,
  pid int not null,
  name varchar(225) not null,
  primary key(id)
);
Copy after login

 Insert test data:

insert onepiece values
  (1,0,'海军'),
  (2,0,'海贼'),
  (3,0,'革命军'),
  (4,1,'青雉'),
  (5,1,'赤犬'),
  (6,1,'黄猿'),
  (7,2,'四皇'),
  (8,2,'七武海'),
  (9,2,'草帽海贼团'),
  (10,9,'索隆'),
  (11,7,'香克斯'),
  (12,8,'多弗朗明哥'),
  (13,8,'克洛克达尔');

Copy after login

Here is the setting in One Piece based on popular science: the world is divided into three major camps: Navy, Pirates, and Revolutionary Army. The navy has generals: Aokiji, Akainu, and Kizaru. The pirates include: the Four Emperors, the Shichibukai, and the Straw Hat Pirates. The Four Emperors have Shanks, the Shichibukai have Doflamingo and Crocodile, and the Straw Hat Pirates have Zoro. (Advertisement: One Piece is really good).

Ultimate goal:

What we are making today are two forms of infinite classification forms, one is a drop-down list type, and the other is a navigation link type. The renderings are uploaded directly:


Drop-down list formula


Navigation Link style

 Example code:

I encapsulated an Unlimited class to call diaplayList() to display the drop-down list form, and call diaplayLink to display the navigation Link category. You can also add (addNodes()) and delete (deleteNodes) categories.

<&#63;php

class Unlimited{
  protected $mysqli;
  public function __construct($config){
    $this->mysqli=new mysqli($config['host'],$config['user'],$config['pwd']);
    $this->mysqli->select_db($config['db']);
    $this->mysqli->set_charset('utf8');
    if ($this->mysqli->connect_errno) {
      echo $this->mysqli->connect_error;
    }
  }  

  private function getList($pid=0,&$result=array(),$spac=0){
    $spac=$spac+2;
    $sql="select * from onepiece where pid={$pid}";
    $rs=$this->mysqli->query($sql);
    while($row=$rs->fetch_assoc()) {
      $row['name']=str_repeat(' &nbsp',$spac).$row['name'];
      $result[]=$row;
      $this->getList($row['id'],$result,$spac);      
    }
    return $result;
  }
  /**
   * 展现下拉列表式分类
   * @return [type] 
   */
  public function displayList(){
    $rs=$this->getList();
    $str="<select name='cate'>";

    foreach ($rs as $key => $val) {
      $str.="<option >{$val['name']}</option>";
    }
    $str.="</select>";
    return $str;
  }

  private function getLink($cid,&$result=array()){
    $sql="select * from onepiece where id={$cid}";
    $rs=$this->mysqli->query($sql);
    if($row=$rs->fetch_assoc()){
      $result[]=$row;
      $this->getLink($row['pid'],$result);
    }
    return array_reverse($result);
  }
  /**
   * 展现导航Link
   * @param [type] $cid [description]
   * @return [type]   [description]
   */
  public function displayLink($cid){
    $rs=$this->getLink($cid);
    $str='';
    foreach ($rs as $val) {
      $str.="<a href=''>{$val['name']}</a>>";
    }

    return $str;
  }
  /**
   * 增加分类
   * @param [type] $pid 父类id
   * @param [type] $name 本类名
   */
  public function addNodes($pid,$name){
    $sql="insert into onepiece values('',{$pid},'".$name."')";
    if($this->mysqli->query($sql)){

      return true;

    }
  }
  /**
   * 删除分类
   * @param [type] $id 本类id
   * @return [type]   
   */
  public function deleteNodes($id){
    $sql="select * from onepiece where pid ={$id}";
    $rs=$this->mysqli->query($sql);
    if($row=$rs->fetch_assoc()){
      $mes="还有子元素,请勿删除";
    }else{
      $sql="delete from onepiece where id={$id}";
      if($this->mysqli->query($sql)){
        $mes="删除成功";
      }
    }
    return $mes;
  }
}

Copy after login

The functions in the class mainly adopt the method of recursive functions. If you understand the recursive functions deeply, the rest will fall into place. I will detail the three ways to implement recursive functions in later sections.

Let’s look at another example:

First create a classification information table:

CREATE TABLE IF NOT EXISTS `category` ( 
 `categoryId` smallint(5) unsigned NOT NULL AUTO_INCREMENT, 
 `parentId` smallint(5) unsigned NOT NULL DEFAULT '0', 
 `categoryName` varchar(50) NOT NULL, 
 PRIMARY KEY (`categoryId`) 
) ; 
Copy after login

Insert some data:

INSERT INTO `category` (`categoryId`, `parentId`, `categoryName`) VALUES 
(1, 0, 'php'), 
(2, 0, 'java'), 
(3, 0, 'c/c++'), 
(4, 1, 'php基础'), 
(5, 1, 'php开源资料'), 
(6, 1, 'php框架'), 
(7, 2, 'java Se'), 
(8, 2, 'java EE'), 
(9, 2, 'java Me'), 
(10, 3, 'c/c++基础编程'), 
(11, 3, 'c/c++系统开发'), 
(12, 3, 'c嵌入式编程'), 
(13, 3, 'c++应用开发'), 
(14, 13, 'c++桌面应用开发'), 
(15, 13, 'c++游戏开发'); 

Copy after login

The following is the php code:

<&#63;php 
/* 
php无限极分类 
*/ 
 
//获取某分类的直接子分类 
function getSons($categorys,$catId=0){ 
  $sons=array(); 
  foreach($categorys as $item){ 
    if($item['parentId']==$catId) 
      $sons[]=$item; 
  } 
  return $sons; 
} 
 
//获取某个分类的所有子分类 
function getSubs($categorys,$catId=0,$level=1){ 
  $subs=array(); 
  foreach($categorys as $item){ 
    if($item['parentId']==$catId){ 
      $item['level']=$level; 
      $subs[]=$item; 
      $subs=array_merge($subs,getSubs($categorys,$item['categoryId'],$level+1)); 
       
    } 
       
  } 
  return $subs; 
} 
 
//获取某个分类的所有父分类 
//方法一,递归 
function getParents($categorys,$catId){ 
  $tree=array(); 
  foreach($categorys as $item){ 
    if($item['categoryId']==$catId){ 
      if($item['parentId']>0) 
        $tree=array_merge($tree,getParents($categorys,$item['parentId'])); 
      $tree[]=$item;  
      break;  
    } 
  } 
  return $tree; 
} 
 
//方法二,迭代 
function getParents2($categorys,$catId){ 
  $tree=array(); 
  while($catId != 0){ 
    foreach($categorys as $item){ 
      if($item['categoryId']==$catId){ 
        $tree[]=$item; 
        $catId=$item['parentId']; 
        break;  
      } 
    } 
  } 
  return $tree; 
} 

//测试 部分 
$pdo=new PDO('mysql:host=localhost;dbname=test','root','8888'); 
$stmt=$pdo->query("select * from category order by categoryId"); 
$categorys=$stmt->fetchAll(PDO::FETCH_ASSOC); 
 
$result=getSons($categorys,1); 
foreach($result as $item) 
  echo $item['categoryName'].'<br>'; 
echo '<hr>'; 
 
$result=getSubs($categorys,0); 
foreach($result as $item) 
  echo str_repeat(' ',$item['level']).$item['categoryName'].'<br>'; 
echo '<hr>'; 
 
$result=getParents($categorys,7); 
foreach($result as $item) 
  echo $item['categoryName'].' >> '; 
echo '<hr>'; 
 
$result=getParents2($categorys,15); 
foreach($result as $item) 
  echo $item['categoryName'].' >> '; 
&#63;> 
Copy after login

Let’s take a look at the final result

Although this article introduces infinite classification using recursion, in fact, it is not recommended for everyone to do so. Everyone knows that the more classifications, the less efficient the recursion will be. This article is just to make everyone better. This is done by understanding recursion.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1044258.htmlTechArticlephp implements infinite classification (recursive method), php recursion I believe many friends who learn php will try to make one Online shopping malls serve as a way to improve one’s skills. Various pairs of products...
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles