PHP uses recursive functions to achieve infinite class classification

Source: Internet
Author: User
I believe many of PHP's many small partners will try to do an online mall as a way to upgrade their own technology. All kinds of product classification, product name and other operations should be handy, then you can try to under the infinite level classification list of the production.

What is an infinite class classification?

Infinite class classification is a kind of classification skills, such as departmental organization, article classification, subject classification and so on to the infinite classification, it is simple to understand the classification is good. In fact, we think about it, the classification of life is simply too many, clothes can be divided into men's and women's clothing, can also be divided into tops and trousers, can also be classified according to age. Classification is everywhere, the classification appears "infinite". I'm not talking about the need for infinite categorization here.

Introduction to the principle of infinite class classification

The infinite classification seemingly "tall", in fact, the principle is very simple. Infinite classification needs not only the subtlety of code, but also the rationality of database design. To satisfy an infinite class of classifications, the database needs to have two required fields, Id,pid. The ID is used to identify itself, and the PID is used to indicate the parent ID. That is, each classification record not only describes itself, but also describes another ID that is most closely related to it. Seemingly complex things are solved by such a small skill.

Gossip doesn't say much, it's time to show examples of this article.

As a fan of crazy pirates, this example I will be "The King of Thieves" character organization to do cases.

Database preparation:

Build Table OnePiece:

Create Table onepiece (    int  auto_increment,    intnotnull,     varchar (225notnull,    primarykey(ID));

Insert test data:

InsertOnePieceValues    (1,0,'Navy'),    (2,0,'Sea Thief'),    (3,0,'Revolutionary Army'),    (4,1,'Green Pheasant'),    (5,1,'Red Dog'),    (6,1,'Yellow Ape'),    (7,2,'Four Kings'),    (8,2,'Seven Wu Hai'),    (9,2,'Straw hat and sea Thief Regiment'),    (Ten,9,'Sauron'),    ( One,7,' the Fox'),    ( A,8,'Brother Doverland'),    ( -,8,'Klockdal');

This is still a popular science in the King inside the set: The world divided into three camps: the Navy, pirates, the revolutionary Army. The Navy has generals: Green Pheasant, Red Dog, Yellow Ape. The Pirates are: Four kings, seven Wu Hai, Straw Hat Pirates regiment. The four Kings have the incense, seven Wu Hai has many flamenco elder brother, the Klockdal, The Straw Hat Thief Regiment has Sauron. (Make an advertisement: The thief Wang Zhen is very good).

Ultimate Purpose:

Today we are making two forms of infinite classification, one is a drop-down list, and the other is navigation link. Directly on the:

Drop-down list navigation link

Instance code:

I encapsulated a unlimited class that calls Diaplaylist () to show the drop-down list form, calling Diaplaylink to show the navigation link category. You can also add (AddNodes ()) and delete (Deletenodes) classifications.

 Phpclassunlimited{protected$mysqli;  Publicfunction__construct ($config){        $this->mysqli=NewMysqli ($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; }    }        PrivatefunctionGetList ($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('  ',$spac).$row[' Name ']; $result[]=$row; $this->getlist ($row[' ID '],$result,$spac); }        return$result; }    /** Show drop-down list category * @return [type]*/ Publicfunctiondisplaylist () {$rs=$this-getList (); $str=""; foreach ($rsas $key = $val) {$str. = "{$val [' name ']} "; } $str. = ""; return$str; }    PrivatefunctionGetLink ($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); }        returnArray_reverse($result); }    /** * Show navigation link * @param [type] $cid [description] * @return [type] [description]*/ PublicfunctionDisplayLink ($cid){        $rs=$this->getlink ($cid); $str=''; foreach($rs as$val) {            $str.="{$val[' Name ']} > "; }        return$str; }    /** * Added category * @param [Type] $PID parent class ID * @param [type] $name this class name*/ PublicfunctionAddNodes ($pid,$name){        $sql= "INSERT into onepiece values ('", {$pid},'".$name."')"; if($this->mysqli->query ($sql)){            returntrue; }    }    /** * Delete category * @param [Type] $id this class ID * @return [type]*/ PublicfunctionDeletenodes ($id){        $sql= "SELECT * from OnePiece where PID ={$id}"; $rs=$this->mysqli->query ($sql); if($row=$rs-Fetch_assoc ()) {            $mes= "There are also child elements, do not delete"; }Else{            $sql= "Delete from onepiece where id={$id}"; if($this->mysqli->query ($sql)){                $mes= "Delete Succeeded"; }        }        return$mes; }}

In the class, the function mainly adopts the recursive function method, if understanding the recursive function deeply, the rest of the parts will be the same. I'll explain in more detail the three ways to implement recursive functions in a later section.

The above introduces PHP using recursive functions to achieve unlimited classification, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.