PHP Implements Infinite class classification (recursive method), PHP recursive _php tutorial

Source: Internet
Author: User

PHP Implements Infinite class classification (recursive method), PHP recursion


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.

To the Internet a search PHP infinite classification, a lot, but a lot of is a, and, write very messy, code a lot, let us how to learn, those are not reliable, or self-ramming drum unlimited pole classification.

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 (  ID int auto_increment,  pid int not NULL,  name varchar (225) is not NULL,  primary KEY (i d));

   Insert test data:

Insert OnePiece values  (1, 0, ' Navy '), (2,0, ' sea Thief '), (3,0, ' the Revolutionary Army '), (4,1, ' Green Pheasant '), (  5,1, ' Red Dog  '), ( 6,1, ' The Yellow Ape '), (  7,2, ' The Four Kings '), (  8,2, ' Seven Wu Hai '), (  9,2, ' Straw Hat Bandit '), (10,9, ' Sauron '), (  11,7, ' the ' Fox  '), ( 12,8, ' Doverland '),  (13,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 Type

  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.

<?phpclass 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 (', $spac). $row [' name '];      $result []= $row;          $this->getlist ($row [' id '], $result, $SPAC);  } return $result;    }/** * Show drop-down list classification * @return [Type] */Public Function displaylist () {$rs = $this->getlist (); $str = "";  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); }/** * Show navigation link * @param [type] $cid [description] * @return [type] [description] */Public Function Displayl    Ink ($cid) {$rs = $this->getlink ($cid);    $str = ";    foreach ($rs as $val) {$str. = "{$val [' name ']}>";  } return $STR; }/** * Add category * @param [Type] $PID parent class ID * @param [type] $name this class name */Public Function addnodes ($pid, $name) {$sq    L= "INSERT into onepiece values (', {$pid}, '". $name. ")";    if ($this->mysqli->query ($sql)) {return true; }}/** * Delete category * @param [Type] $id this class ID * @return [type] */Public Function deletenodes ($id) {$sql = "Selec    T * 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.

Let's look at one more example:

First set up the classification information table:

CREATE TABLE IF not EXISTS ' category ' (  ' categoryId ' smallint (5) unsigned not NULL auto_increment,  ' ParentID ' smal Lint (5) unsigned not null DEFAULT ' 0 ',  ' categoryname ' varchar (a) NOT NULL,  

Insert several data:

Here is the PHP code:

<?php/* PHP infinite Pole classification *//Get Direct sub-classification function getsons for a classification ($categorys, $catId =0) {$sons =array ();   foreach ($categorys as $item) {if ($item [' ParentID ']== $catId) $sons []= $item; } return $sons;   }//Get all sub-classifications of a category 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;   }//Get all Parent class//method one for a category, recursive function getparents ($categorys, $catId) {$tree =array (); foreach ($categorys as $item) {if ($item [' categoryId ']== $catId) {if ($item [' ParentID ']>0) $tree =array_me       Rge ($tree, Getparents ($categorys, $item [' ParentID ']);        $tree []= $item;      Break }} return $tree;   }//Method Two, iterative 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; }//Test part $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); A foreach ($result as $item) echo $item [' CategoryName ']. '
'; Echo '; $result =getsubs ($categorys, 0); foreach ($result as $item) echo str_repeat (", $item [' Level ']). $item [' CategoryName ']. '
'; Echo '; $result =getparents ($categorys, 7); foreach ($result as $item) echo $item [' CategoryName ']. ' >> '; Echo '; $result =getparents2 ($categorys, 15); foreach ($result as $item) echo $item [' CategoryName ']. ' >> ';?>

Look at the final result.

Although this article introduces the use of recursive implementation of the infinite class classification, but in fact, do not recommend that you do so, we know that the classification of more, recursive efficiency is low, this article is just to let everyone better understand recursion to do so.

http://www.bkjia.com/PHPjc/1044258.html www.bkjia.com true http://www.bkjia.com/PHPjc/1044258.html techarticle PHP Implementation of infinite Class classification (recursive method), PHP recursive believe that many of PHP's many small partners will try to do an online shopping mall as a way to upgrade their own technology. Various pairs of commodities ...

  • 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.