PHP unlimited classification implementation project_php tutorial

Source: Internet
Author: User
PHP unlimited classification implementation program. 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. the database is designed to sort data in a specific format, mysql lookup is used. 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. the database design arranges the indexes in a specific format, then use mysql to query the key function: concat. Simple program implementation

First, let's assume there is such a three-level classification: news> PHP News> PHP6.0.
If you want to find the news "PHP6.0 has come out", click the news first, and then click the PHP News.

We can find out, that is, we can look down through the grandfather class level-1, in turn we just

If you know the parent class of a subclass, you can find it. In this way, we can design multiple databases.

The field of a parent class id can be used to implement the unlimited classification function.

The code is as follows:
// Create a table "class"
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 no parent class exists, I set f_id to 0.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (1, 0, 'news '); // The id field automatically increases without writing a value.

// 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.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (2, 1, 'php News ');

// Then we insert the 'php6. 0' category into the database. the id of its parent class 'php news' is 2, so its f_id is set to 2.
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.
// Assume that you 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, its f_id is also set to 0;
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.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (5, 4, 'php techno ');

// When we see this, we should all understand how to insert various categories into the database. I will not give an example.

We already know how to insert each category into the database, and how to list each category?

The code is as follows:

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']."
"; // In this way, every major category is recycled.
}
// 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 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]."
"; // $ 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.
}
}
}
?>


Three field IDs, parentid, name
The algorithm is also very simple recursion. it was silly to use recursion in the past. it should be silly to say that, because in recursion, all sub-classes are obtained by querying data tables, which has recently been enlightened, think of a method that everyone on Earth can think of. below is the code, a class

The code is as follows:

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;
}
}

Saving the structure into an array through a query and performing recursive operations on the array undoubtedly greatly improves the program running efficiency.
Easy to use code


...

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.