Php + mysql implement unlimited classification instance details

Source: Internet
Author: User

Php + mysql implement unlimited classification instance details

This article mainly introduces how to implement unlimited classification in php + mysql. The instance analyzes the specific implementation steps of mysql database design, database operations, and infinitus classification, which is of great practical value, for more information, see

 

 

This example describes how to implement unlimited classification in php + mysql. Share it with you for your reference. The specific analysis is as follows:

1. The database performs a unique index by setting the parent class ID, and then uses the recursive call of the function to implement unlimited classification;

2. database design is arranged in a specific format, and then mysql is used to query key functions: concat. The program implementation is relatively simple. First, we assume that there is such a level-3 classification, news> PHP News> PHP6.0.

If we want to find the news "PHP6.0 has come out", we can click the news first, and then click the PHP news to find out. That is to say, we can find the news at the top level through the grandfather class, in turn, as long as we know the parent class of a subclass, we can find it, in this way, when designing a database, we can design a parent class id field to implement the unlimited classification function.

The database code is as follows:

Here we create a table "class"

The Code is as follows:

Create table 'class '(
'Id' int (11) not null auto_increment COMMENT 'category id ',
'F _ id' int (11) not null comment 'parent id ',
'Name' varchar (25) collate gbk_bin not null comment 'category name ',
Primary key ('id ')
) ENGINE = MyISAM default charset = gbk COLLATE = gbk_bin AUTO_INCREMENT = 1;


First, we insert the 'News' big classification into the database. Because 'News' is the largest category and there is no parent class above, I set its f_id to 0.

The Code is as follows:

Insert into 'class' ('id', 'f _ id', 'name') VALUES (1, 0, 'News '); // The id field is automatically increased and can be left empty.

 

Then we insert the 'php news 'category into the database. The id of its parent class 'News' is 1, so its f_id is set to 1.

The Code is as follows:

Insert into 'class' ('id', 'f _ id', 'name') VALUES (2, 1, 'php News ');

 

Then we inserted the 'php6. 0. 0 'category into the database. Its parent class 'php news' has a id of 2, so its f_id is set to 2.

The Code is as follows:

Insert into 'class' ('id', 'f _ id', 'name') VALUES (3, 2, 'php6. 0 ');

 

Similarly, We can insert categories all the time to achieve unlimited classification.

We can find that the key to inserting a category is to find the id of the parent class of the category and use it as the value of the f_id field of the category.

Suppose we want to insert the same level of classifier as 'News', that is to say, it is also the largest classification. If there is no parent class above, then its f_id is also set to 0;

Copy the Code as follows:

Insert into 'class' ('id', 'f _ id', 'name') VALUES (4, 0, 'technical ');

 

There is another classification of 'php' under 'tech'. So how can we insert it? First, find the id of the parent class 'tech' of 'php, and use it as the value of your f_id field.

The Code is as follows:

Insert into 'class' ('id', 'f _ id', 'name') VALUES (5, 4, 'php techno ');

 

When we see this, we should all know how to insert various categories into the database, so we will not give an example. We already know how to insert categories into the database, then how can we list all categories?

The Code is as follows:

<? Php
Header ("Content-type: text/html; charset = UTF-8 ");
$ Db = new mysqli ("localhost", "root", "", "news_php100"); // instantiate a database connection. Before using this method, make sure that the mysqli class library has been loaded or you can use mysql_connect to connect.
If (mysqli_connect_errno ()){
Echo "link failed:". mysqli_connect_error ();
Exit ();}
$ Db-> query ("set names utf8 ");
$ Result = $ db-> query ("select name from class where f_id = 0"); // you can find the f_id = 0 category, that is, to find each category.
While ($ row = $ result-> fetch_assoc ()){
Echo $ row ['name']. "<br>"; // loop every category.
}
// We can loop the subcategories of news.
$ Result = $ db-> query ("select * from class where f_id = 1"); // you can find the classification of f_id = 1, that is, the subclass of 'News.
While ($ row = $ result-> fetch_assoc ()){
Echo $ row ['name']."
"; // In this way, the subcategory of 'News' is recycled. Note: It is only a subclass, not a Child class.
}
// Write it here and we will find a problem. If this category is of the 10th level, do we need to write 10 loops to cycle every subclass of it? If it is more multi-level classification, it is obviously unrealistic to write.
// What can be done? We can write a recursive function that uses f_id as a parameter and continuously loops through each f_id value, that is, loops through the subclass of each f_id value.
// First, we store the values of each classification in a two-dimensional array, which is useful in the following recursive functions.
$ Result = $ db-> query ("select * from class ");
While ($ row = $ result-> fetch_assoc ()){
$ Arr [] = array ($ row [id], $ row [f_id], $ row [name]); // each row stores a category id, f_id, name.
}
Function fenlei ($ f_id = 0) {// $ f_id is initialized to 0, that is, the cycle starts from the maximum classification.
Global $ arr; // declare $ arr as a global variable for reference in the function.
For ($ I = 0; $ I <count ($ arr); $ I ++) {// loops each category.
If ($ arr [$ I] [1] = $ f_id) {// $ arr [$ I] [1] indicates the f_id value of the $ I + 1 category. Start with $ f_id = 0, that is, output the f_id = 0 category.
Echo $ arr [$ I] [2]. "<br>"; // $ arr [$ I] [1] indicates the name of the $ I + 1 category.
Fenlei ($ arr [$ I] [0]); // $ arr [$ I] [1] indicates the id value of the $ I + 1 category. Recursion, that is, using your id as the f_id parameter to recycle its subclass.
}
}
}
?>


The three field IDs, parentid, name, and algorithms are also simple recursion. Previously, they were silly when recursion was used. It should be said that they were silly because in recursion, data tables are queried to obtain all the child classes, I was enlightened recently and thought of a method that everyone on Earth can think of. below is the code, a class, and the code is as follows:

Copy the Code as follows:

<? Php
Class Tree {

/**
* All category information queried from the database
* @ Var array
*/
Var $ arr;
/**
* Format:
* Var $ arr = array (
1 => array ('id' => '1', 'parentid' => 0, 'name' => 'level 1 topic 1 '),
2 => array ('id' => '2', 'parentid' => 0, 'name' => 'level 1 column 2 '),
3 => array ('id' => '3', 'parentid' => 1, 'name' => 'second-level topic 1 '),
);*/

/**
* Output structure
* @ Var array
*/
Var $ tree = array ();
/**
* Depth of tree Recursion
* @ Var int
*/
Var $ deep = 1;

/**
* Generate tree-like modifiers
* @ Var array
*/
Var $ icon = array ('│', 'hangzhou', 'hangzhou ');
/**
* Generate the subtree structure of the specified id
* @ Param int $ rootid the id of the tree structure to be obtained
* @ Param string $ add the prefix used in Recursion
* @ Param bool $ parent_end identifies whether the upper-level category is the last one
*/
Function getTree ($ rootid = 0, $ add = ", $ parent_end = true ){
$ Is_top = 1;
$ Child_arr = $ this-> getChild ($ rootid );
If (is_array ($ child_arr )){
$ Cnt = count ($ child_arr );
Foreach ($ child_arr as $ key => $ child ){
$ Cid = $ child ['id'];
$ Child_child = $ this-> getChild ($ cid );
If ($ this-> deep> 1 ){
If ($ is_top = 1 & $ this-> deep> 1 ){
$ Space = $ this-> icon [1];
If (! $ Parent_end)
$ Add. = $ this-> icon [0];
Else $ add. = '';
}

If ($ is_top = $ cnt ){
$ Space = $ this-> icon [2];
$ Parent_end = true;
} Else {
$ Space = $ this-> icon [1];
$ Parent_end = false;
}
}
$ This-> tree [] = array ('spacer' => $ add. $ k. $ space,
'Name' => $ child ['name'],
'Id' => $ cid
);
$ Is_top ++;

$ This-> deep ++;
If ($ this-> getChild ($ cid ))
$ This-> getTree ($ cid, $ add, $ parent_end );
$ This-> deep -;
}
}
Return $ this-> tree;
}

/**
* Get the array of lower-level categories
* @ Param int $ root
*/
Function getChild ($ root = 0 ){

$ A = $ child = array ();
Foreach ($ this-> arr as $ id => $ ){
If ($ a ['parentid'] = $ root ){
$ Child [$ a ['id'] = $;
}
}
Return $ child? $ Child: false;
}
/**
* Set the source array
* @ Param $ arr
*/
Function setArr ($ arr = array ()){
$ This-> arr = $ arr;
}
}
?>


By saving the structure into an array through a query, and performing recursive operations on the array, the program running efficiency is greatly improved, and the code is very simple.

 

I hope this article will help you with php programming.

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.