Php implements unlimited classification (recursive method) and php Recursion
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 = "<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 );} /*** display navigation 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 ;} /*** 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 ['categoryna Me ']. '<br>'; echo '
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.