search
HomeBackend DevelopmentPHP Tutorialphp实现无限级分类(递归方法)_PHP

相信很多学php的很多小伙伴都会尝试做一个网上商城作为提升自己技术的一种途径。各种对商品分类,商品名之类的操作应该是得心应手,那么就可以尝试下无限级分类列表的制作了。

到网上一搜php无限极分类,很多,但好多都是一个,并且,写的很乱,代码很多,让我们怎么学习嘛,那些都不靠谱,还是自己捣鼓捣鼓无限极分类了。

  什么是无限级分类?

  无限级分类是一种分类技巧,例如部门组织,文章分类,学科分类等常用到无限级分类,将其简单理解成分类就好了。其实我们仔细想一下,生活中的分类简直太多了,衣服可以分为男装和女装,也可以分为上衣和裤子,也可以根据年龄段分类。分类无处不在,分类显得“无限”。我这里就不说无限分类的必要性了。

  无限级分类原理简介

  无限分类看似"高大上",实际上原理是非常简单的 。无限分类不仅仅需要代码的巧妙性,也要依托数据库设计的合理性。要满足无限级分类,数据库需要有两个必须的字段,id,pid。id用来标识自身,而pid则是用来表明父级id。也就是说,每个分类记录不仅描述了自身,还描述了与其关心最为紧密的另一个id。看似复杂的事情被这样一个小技巧解决了。

  闲话不多说,该展现本文的实例了。

  作为一个狂热海贼迷,这篇的实例我就以《海贼王》人物组织做案例。

  数据库准备: 

  建表onepiece:

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

   插入测试数据:

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,'克洛克达尔');

  这里还是科普下海贼王里面的设定:世界分为三大阵营:海军,海贼,革命军。海军有大将:青雉,赤犬,黄猿。海贼有:四皇,七武海,草帽海贼团。四皇有香克斯,七武海有多弗朗明哥,克洛克达尔,草帽海贼团有索隆。(打个广告:海贼王真的很好看)。

  最终目的:

  我们今天制作的是两种形式的无限级分类形式,一种是下拉列表式,一种则是导航Link式的。直接上效果图了:


下拉列表式


导航Link式

  实例代码:

  我封装了一个Unlimited类,用来调用diaplayList()展现下拉列表形式,调用diaplayLink展现导航Link分类。也可以增加(addNodes())和删除(deleteNodes)分类。

<&#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;
  }
}

  类中函数主要采取了递归函数的方法,如果理解深刻理解递归函数,其余的部分也就水到渠成了。我会在后面的部分详细介绍实现递归函数的三种方法。

 我们再来看一个实例:

首先建立分类信息表:

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`) 
) ; 

插入若干数据:

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++游戏开发'); 

下面是php代码:

<&#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;> 

看下最终结果吧

虽然本文介绍的是使用递归来实现的无限级分类,但实际上,并不推荐大家这么做,大家知道分类多了,递归效率也就低了,本文这里仅仅是为了让大家更好的理解递归才这么做的。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.