Php implements unlimited classification (recursive method)

Source: Internet
Author: User
Tags php basics
When you are learning php Infinitus classification, I think it is difficult for everyone to say "difficult". so I am still reading it. because work is necessary, research is required. I believe many php students will try to create an online store as a way to improve their technology. Various operations such as product classification and product name should be handy, so you can try to create an unlimited classification list.

There are many php Infinitus categories searched on the Internet, but many of them are one. In addition, they are messy and have a lot of code. how can we learn them? these are unreliable, I am still using the Infinitus category.

What is an infinite classification?

Unlimited classification is a kind of classification technique, such as department organization, article classification, and Subject Classification. it is good to simply understand it as a classification. As a matter of fact, there are too many categories in our life. clothes can be divided into men's and women's clothing, jackets and trousers, or by age group. Classification is everywhere, and classification is "unlimited ". I will not mention the necessity of unlimited classification here.

Introduction to the principle of unlimited classification

Infinite classification seems to be "too high". In fact, the principle is very simple. Unlimited classification requires not only clever code, but also the rationality of database design. To meet the infinite classification requirements, the database must have two Required fields: id and pid. Id is used to identify itself, while pid is used to indicate the parent level id. That is to say, each classification record not only describes itself, but also describes another id most closely related to it. The seemingly complex things have been solved by such a small trick.

I will not talk much about it. it is time to show the examples in this article.

As an avid Pirate fan, I will use the case of one piece as an example.

Database preparation:

Create an onepiece table:

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

Insert test data:

Insert onepiece values (, 'haibin'), (, 'pirate '), (, 'Revolutionary Army'), (, 'qingline, 'shorge'), (6, 1, 'Yellow ape '), (7, 2, '4 Huang'), (8, 2, '7 Wu Hai'), (9, 2, 'straw Captain Pirate group '), (, 'solon'), (11,7, 'sysysys'), (12,8, 'doflaminggo'), (, 'lockdal ');

Here is the setting in the popular science Thief: The world is divided into three camps: the Navy, the pirate, and the revolutionary army. There are generals in the Navy: Qingyi, chidog, and Huang yuan. Pirates include: Four Emperors, seven Wuhai, and straw hats. The four emperors have the fragrant keys, and the seven Wuhai have the freeloming brother, the lockdal, and the straw hat pirate troupe have Suo long. (Advertisement: One piece is really nice ).

Ultimate goal:

What we made today is two forms of unlimited classification, one is drop-down classification, and the other is navigation Link. Directly:


Drop-Down examples


Navigation Link

Instance code:

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

<? 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;}/*** display the drop-down type category * @ return [type] */public function displayList () {$ rs = $ this-> getList (); $ str =""; Foreach ($ rs as $ key => $ val) {$ str. ="{$ Val ['name']}";}$ 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 );} /*** display navigation Link * @ param [type] $ cid [description] * @ return [type] [description] */public function displayLink ($ 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 of this class */public function addNodes ($ pid, $ name) {$ SQL = "insert into onepiece values ('', {$ pid },'". $ name. "')"; if ($ this-> mysqli-> query ($ SQL) {return true ;}} /*** delete Category ** @ param [type] $ id this Category 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 = "There are sub-elements, please do not delete ";} else {$ SQL = "delete from onepiece where id = {$ id}"; if ($ this-> mysqli-> query ($ SQL )) {$ mes = "deleted successfully" ;}} return $ mes ;}}

In the class, functions mainly adopt recursive functions. if you have a deep understanding of recursive functions, the rest will become a problem. I will introduce in detail the three methods for implementing recursive functions in the following sections.

Let's look at an 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`) ) ; 

Insert data:

Insert into 'category' ('categoryid', 'parentid', 'categoryname') VALUES (1, 0, 'php'), (2, 0, 'Java '), (3, 0, 'C/c ++ '), (4, 1, 'php basics'), (5, 1, 'php open source information'), (6, 1, 'php framework'), (7, 2, 'Java se'), (8, 2, 'Java EE '), (9, 2, 'Java me'), (10, 3, 'C/c ++ basic programming '), (11, 3, 'C/c ++ system developer '), (12, 3, 'c embedded programming '), (13, 3, 'c ++ application developer'), (14, 13, 'C ++ desktop application developer'), (15, 13, 'c ++ Game Developer ');

The following is the php code:

<? Php/* php Infinitus classification * // Obtain the direct subcategory of a certain category. 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 ;}// obtain all parent categories of a category // method 1, recursive 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 ;}// method 2, iteration function getParents2 ($ categorys, $ catId) {$ tree = array (); while ($ ca TId! = 0) {foreach ($ categorys as $ item) {if ($ item ['categoryid'] = $ catId) {$ tree [] = $ item; $ catId = $ item ['parentid']; break ;}}return $ tree;} // test section $ pdo = new PDO ('MySQL: host = localhost; dbname = test', 'root', '000000'); $ 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'].'
'; 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']. '>';?>

Check the final result.

Although this article describes the use of recursion to implement unlimited classification, we do not recommend that you do this. as you know, there are more classifications and the recursion efficiency is low, this article is only intended for better understanding of recursion.

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.