Home Backend Development PHP Tutorial php利用递归函数实现无限级归类

php利用递归函数实现无限级归类

Jun 13, 2016 pm 12:23 PM
gt mysqli return this

php利用递归函数实现无限级分类

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

  什么是无限级分类?

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

  无限级分类原理简介

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

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

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

  数据库准备: 

  建表onepiece:

<span style="color: #0000ff;">create</span> <span style="color: #0000ff;">table</span><span style="color: #000000;"> onepiece(    id </span><span style="color: #0000ff;">int</span><span style="color: #000000;"> auto_increment,    pid </span><span style="color: #0000ff;">int</span> <span style="color: #808080;">not</span> <span style="color: #0000ff;">null</span><span style="color: #000000;">,    name </span><span style="color: #0000ff;">varchar</span>(<span style="color: #800000; font-weight: bold;">225</span>) <span style="color: #808080;">not</span> <span style="color: #0000ff;">null</span><span style="color: #000000;">,    </span><span style="color: #0000ff;">primary</span> <span style="color: #0000ff;">key</span><span style="color: #000000;">(id));</span>
Copy after login

   插入测试数据:

<span style="color: #0000ff;">insert</span> onepiece <span style="color: #0000ff;">values</span><span style="color: #000000;">    (</span><span style="color: #800000; font-weight: bold;">1</span>,<span style="color: #800000; font-weight: bold;">0</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">海军</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">2</span>,<span style="color: #800000; font-weight: bold;">0</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">海贼</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">3</span>,<span style="color: #800000; font-weight: bold;">0</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">革命军</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">4</span>,<span style="color: #800000; font-weight: bold;">1</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">青雉</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">5</span>,<span style="color: #800000; font-weight: bold;">1</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">赤犬</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">6</span>,<span style="color: #800000; font-weight: bold;">1</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">黄猿</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">7</span>,<span style="color: #800000; font-weight: bold;">2</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">四皇</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">8</span>,<span style="color: #800000; font-weight: bold;">2</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">七武海</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">9</span>,<span style="color: #800000; font-weight: bold;">2</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">草帽海贼团</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">10</span>,<span style="color: #800000; font-weight: bold;">9</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">索隆</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">11</span>,<span style="color: #800000; font-weight: bold;">7</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">香克斯</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">12</span>,<span style="color: #800000; font-weight: bold;">8</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">多弗朗明哥</span><span style="color: #ff0000;">'</span><span style="color: #000000;">),    (</span><span style="color: #800000; font-weight: bold;">13</span>,<span style="color: #800000; font-weight: bold;">8</span>,<span style="color: #ff0000;">'</span><span style="color: #ff0000;">克洛克达尔</span><span style="color: #ff0000;">'</span>);
Copy after login

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

  最终目的:

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

下拉列表式导航Link式

  实例代码:

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

  

<span style="color: #000000;">php</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Unlimited{    </span><span style="color: #0000ff;">protected</span> <span style="color: #800080;">$mysqli</span><span style="color: #000000;">;    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$config</span><span style="color: #000000;">){        </span><span style="color: #800080;">$this</span>->mysqli=<span style="color: #0000ff;">new</span> mysqli(<span style="color: #800080;">$config</span>['host'],<span style="color: #800080;">$config</span>['user'],<span style="color: #800080;">$config</span>['pwd'<span style="color: #000000;">]);        </span><span style="color: #800080;">$this</span>->mysqli->select_db(<span style="color: #800080;">$config</span>['db'<span style="color: #000000;">]);        </span><span style="color: #800080;">$this</span>->mysqli->set_charset('utf8'<span style="color: #000000;">);        </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$this</span>->mysqli-><span style="color: #000000;">connect_errno) {            </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$this</span>->mysqli-><span style="color: #000000;">connect_error;        }    }        </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span> getList(<span style="color: #800080;">$pid</span>=0,&<span style="color: #800080;">$result</span>=<span style="color: #0000ff;">array</span>(),<span style="color: #800080;">$spac</span>=0<span style="color: #000000;">){        </span><span style="color: #800080;">$spac</span>=<span style="color: #800080;">$spac</span>+2<span style="color: #000000;">;        </span><span style="color: #800080;">$sql</span>="select * from onepiece where pid={<span style="color: #800080;">$pid</span>}"<span style="color: #000000;">;        </span><span style="color: #800080;">$rs</span>=<span style="color: #800080;">$this</span>->mysqli->query(<span style="color: #800080;">$sql</span><span style="color: #000000;">);        </span><span style="color: #0000ff;">while</span>(<span style="color: #800080;">$row</span>=<span style="color: #800080;">$rs</span>-><span style="color: #000000;">fetch_assoc()) {            </span><span style="color: #800080;">$row</span>['name']=<span style="color: #008080;">str_repeat</span>(' &nbsp',<span style="color: #800080;">$spac</span>).<span style="color: #800080;">$row</span>['name'<span style="color: #000000;">];            </span><span style="color: #800080;">$result</span>[]=<span style="color: #800080;">$row</span><span style="color: #000000;">;            </span><span style="color: #800080;">$this</span>->getList(<span style="color: #800080;">$row</span>['id'],<span style="color: #800080;">$result</span>,<span style="color: #800080;">$spac</span><span style="color: #000000;">);                    }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$result</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 展现下拉列表式分类     * @return [type]      </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> displayList(){        </span><span style="color: #800080;">$rs</span>=<span style="color: #800080;">$this</span>-><span style="color: #000000;">getList();        </span><span style="color: #800080;">$str</span>="<select name="cate">"<span style="color: #000000;">;        </span><span style="color: #0000ff;">foreach</span> (<span style="color: #800080;">$rs</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$key</span> => <span style="color: #800080;">$val</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$str</span>.="<option>{<span style="color: #800080;">$val</span>['name']}</option>"<span style="color: #000000;">;        }        </span><span style="color: #800080;">$str</span>.="</select>"<span style="color: #000000;">;        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$str</span><span style="color: #000000;">;    }    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">function</span> getLink(<span style="color: #800080;">$cid</span>,&<span style="color: #800080;">$result</span>=<span style="color: #0000ff;">array</span><span style="color: #000000;">()){        </span><span style="color: #800080;">$sql</span>="select * from onepiece where id={<span style="color: #800080;">$cid</span>}"<span style="color: #000000;">;        </span><span style="color: #800080;">$rs</span>=<span style="color: #800080;">$this</span>->mysqli->query(<span style="color: #800080;">$sql</span><span style="color: #000000;">);        </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$row</span>=<span style="color: #800080;">$rs</span>-><span style="color: #000000;">fetch_assoc()){            </span><span style="color: #800080;">$result</span>[]=<span style="color: #800080;">$row</span><span style="color: #000000;">;            </span><span style="color: #800080;">$this</span>->getLink(<span style="color: #800080;">$row</span>['pid'],<span style="color: #800080;">$result</span><span style="color: #000000;">);        }        </span><span style="color: #0000ff;">return</span> <span style="color: #008080;">array_reverse</span>(<span style="color: #800080;">$result</span><span style="color: #000000;">);    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 展现导航Link     * @param  [type] $cid [description]     * @return [type]      [description]     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> displayLink(<span style="color: #800080;">$cid</span><span style="color: #000000;">){        </span><span style="color: #800080;">$rs</span>=<span style="color: #800080;">$this</span>->getLink(<span style="color: #800080;">$cid</span><span style="color: #000000;">);        </span><span style="color: #800080;">$str</span>=''<span style="color: #000000;">;        </span><span style="color: #0000ff;">foreach</span> (<span style="color: #800080;">$rs</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$val</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$str</span>.="<a href="">{<span style="color: #800080;">$val</span>['name']}</a>>"<span style="color: #000000;">;        }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$str</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 增加分类     * @param [type] $pid  父类id     * @param [type] $name 本类名     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> addNodes(<span style="color: #800080;">$pid</span>,<span style="color: #800080;">$name</span><span style="color: #000000;">){        </span><span style="color: #800080;">$sql</span>="insert into onepiece values('',{<span style="color: #800080;">$pid</span>},'".<span style="color: #800080;">$name</span>."')"<span style="color: #000000;">;        </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$this</span>->mysqli->query(<span style="color: #800080;">$sql</span><span style="color: #000000;">)){            </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">;        }    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 删除分类     * @param  [type] $id 本类id     * @return [type]          </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> deleteNodes(<span style="color: #800080;">$id</span><span style="color: #000000;">){        </span><span style="color: #800080;">$sql</span>="select * from onepiece where pid ={<span style="color: #800080;">$id</span>}"<span style="color: #000000;">;        </span><span style="color: #800080;">$rs</span>=<span style="color: #800080;">$this</span>->mysqli->query(<span style="color: #800080;">$sql</span><span style="color: #000000;">);        </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$row</span>=<span style="color: #800080;">$rs</span>-><span style="color: #000000;">fetch_assoc()){            </span><span style="color: #800080;">$mes</span>="还有子元素,请勿删除"<span style="color: #000000;">;        }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{            </span><span style="color: #800080;">$sql</span>="delete from onepiece where id={<span style="color: #800080;">$id</span>}"<span style="color: #000000;">;            </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$this</span>->mysqli->query(<span style="color: #800080;">$sql</span><span style="color: #000000;">)){                </span><span style="color: #800080;">$mes</span>="删除成功"<span style="color: #000000;">;            }        }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$mes</span><span style="color: #000000;">;    }}</span>
Copy after login

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

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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

Solution to PHP Fatal error: Call to undefined function mysqli_connect() Solution to PHP Fatal error: Call to undefined function mysqli_connect() Jun 23, 2023 am 09:40 AM

When writing web applications using PHP, a MySQL database is often used to store data. PHP provides a way to interact with the MySQL database called MySQLi. However, sometimes when using MySQLi, you will encounter an error message, as shown below: PHPFatalerror:Calltoundefinedfunctionmysqli_connect() This error message means that PHP cannot find my

PHP PDO vs. mysqli: compare and contrast PHP PDO vs. mysqli: compare and contrast Feb 19, 2024 pm 12:24 PM

PDOPDO is an object-oriented database access abstraction layer that provides a unified interface for PHP, allowing you to use the same code to interact with different databases (such as Mysql, postgresql, oracle). PDO hides the complexity of underlying database connections and simplifies database operations. Advantages and Disadvantages Advantages: Unified interface, supports multiple databases, simplifies database operations, reduces development difficulty, provides prepared statements, improves security, supports transaction processing Disadvantages: performance may be slightly lower than native extensions, relies on external libraries, may increase overhead, demo code uses PDO Connect to mysql database: $db=newPDO("mysql:host=localhost;dbnam

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

What should I do if php cannot connect to mysqli? What should I do if php cannot connect to mysqli? Nov 09, 2022 am 10:07 AM

Solution to php unable to connect to mysqli: 1. Open the "php.ini" file; 2. Find "mysqli.reconnect"; 3. Change "mysqli.reconnect = OFF" to "mysqli.reconnect = on".

PHP Warning: mysqli_connect(): (HY000/2002): Solution to Connection refused PHP Warning: mysqli_connect(): (HY000/2002): Solution to Connection refused Jun 23, 2023 am 08:54 AM

If you encounter the following error message when using PHP to connect to a MySQL database: PHPWarning:mysqli_connect():(HY000/2002):Connectionrefused, then you can try to solve this problem by following the steps below. To confirm whether the MySQL service is running normally, you should first check whether the MySQL service is running normally. If the service is not running or fails to start, it may cause a connection refused error. you can

See all articles