PHP Unlimited Classification Implementation Program

Source: Internet
Author: User
Tags foreach

First of all we assume that there is such a level three classification, news →php News →php6.0 out.
If we're looking for the news "PHP6.0 out", we'll click on the news and then click on the PHP news.

We can find out, which means we can look down through the grandfather class, and in turn we just

Know a subclass of the parent class, you can find it out. So we can design a database with more

A field with the ID of a parent class can be used to implement an infinite classification function.

  code is as follows copy code
//" We build a table " Class '
CREATE TABLE ' class ' (
  ' id ' int (one) not NULL auto_increment COMMENT ' category ID ',
  ' f_id ' int (11 Not NULL COMMENT ' parent ID ',
  ' name ' varchar ' collate gbk_bin NOT null COMMENT ' category name ',
  PRIMARY KEY&NB Sp (' ID ')
) engine=myisam  DEFAULT charset=gbk collate=gbk_bin auto_increment=1;


First we insert the big category of ' News ' into the database, because ' news ' is the largest category, there is no parent class, so I set its f_id to 0.
INSERT into ' class ' (' id ', ' f_id ', ' name ') VALUES (1, 0, ' News '); ID This field is automatically grown, you can not write the value.

Then we insert the category "PHP News" into the database, and its parent class ' News ' ID 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 ' PHP6.0 out ' in the database, and its parent class ' PHP News ' ID is 2, so its f_id is set to 2.
INSERT into ' class ' (' id ', ' f_id ', ' name ') VALUES (3, 2, ' PHP6.0 out ');

In the same way, we can continue to insert the category down, and we reach an infinite classification.
We can see that the key to inserting a taxonomy is to find the ID of the parent class for this category, and then as the value of the f_id field for that category.
Suppose you want to insert the category ' technology ' at the same level as ' news ', which means it is also the largest category, with no parent on it, and its f_id is also set to 0;
INSERT into ' class ' (' id ', ' f_id ', ' name ') VALUES (4, 0, ' technology ');

Under ' technology ' there is also a classification of ' PHP technology ', so how do we insert it, first find the ' PHP technology ' of the parent ' technology ' ID, and then as the value of their own f_id fields.
INSERT into ' class ' (' id ', ' f_id ', ' name ') VALUES (5, 4, ' PHP technology ');

See here, presumably you should all understand how to insert various categories into the database. is no longer an example.

We already know how to insert various categories into the database, so how do we list the categories?

The code is as follows Copy Code

<?php
Header ("Content-type:text/html;charset=utf-8");
$db =new mysqli ("localhost", "root", "" "," news_php100 "); Instantiates a database connection. Make sure that you have loaded the Mysqli class library before using this, or connect it in mysql_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"); Find the classification of f_id=0, which is to find each large class.
while ($row = $result->fetch_assoc ()) {
echo $row [' name '].        <br> "; This loops out every big class.
}
Again, we can recycle the news subclass.
$result = $db->query ("SELECT * from class where f_id=1"); Find the f_id=1 category, which is to find the ' news ' subclass.
while ($row = $result->fetch_assoc ()) {
echo $row [' name '].
"; This will be the ' news ' of the sub-class loop out. Note: Just subclasses, excluding Sun Tzu classes.
}
Writing here, we will find a problem, if this classification is 10 levels of classification, do we have to write 10 loops to each of its subclasses loop out? If it is more level classification, this writing is obviously unrealistic.
What is the solution? We can write a recursive function, pass the f_id as a parameter, and loop through each of the f_id values, that is, to loop through the subclasses of each f_id value.
First we save the values of each category in a two-dimensional array, which is useful in the recursive function below.
$result = $db->query ("SELECT * from class");
while ($row = $result->fetch_assoc ()) {
$arr []=array ($row [id], $row [f_id], $row [name]); Each row holds a category of id,f_id,name information.
}
function Fenlei ($f _id=0) {//$f _id initialized to 0, which is the loop starting from the largest category.
Global $arr; Declaring $arr as a global variable can be referenced in a function.
For ($i =0 $i <count ($arr), $i + +) {//loops each category.
if ($arr [$i][1]== $f _id) {//$arr [$i][1] represents the f_id value of the $I+1 classification. Start $f_id=0, that is, the output of the f_id=0 classification.
echo $arr [$i][2]. " <br> "; $arr [$i][1] represents the value of the name of the $i+1 category.
Fenlei ($arr [$i][0]); $arr [$i][1] represents the value of the ID of the $i+1 category. Recursion, which is to recycle your own subclass as a f_id parameter.
}
}
}
?>


Three field IDs, ParentID, name
The algorithm is also very simple recursion, used to recursive time is very silly, it should be said that extremely silly, because in recursion through the query data table to get all the subclasses, recently enlightened, think of a earth people can get the method, the following is code, a class

The code is as follows Copy Code

<?php
Class Tree {

/**
* All the classified information from the database query
* @var Array
*/
var $arr;
/**
* Following format
* var $arr = array (
1 => Array (' ID ' => ' 1′, ' parentid ' =>0, ' name ' => ' one-level column one '),
2 => Array (' ID ' => ' 2′, ' parentid ' =>0, ' name ' => ' one-level column II '),
3 => Array (' ID ' => ' 3′, ' parentid ' =>1, ' name ' => ' Level two column one '),
);*/

/**
* Output Structure
* @var Array
*/
var $tree = array ();
/**
* Depth of recursive tree
* @var int
*/
var $deep = 1;

/**
* Create a tree-shaped cosmetic symbol
* @var Array
*/
var $icon = array (' │ ', ' ├ ', ' └ ');
/**
* Generate the subordinate tree structure of the specified ID
* @param int $rootid to get the ID of the tree structure
* @param string $add prefix used in recursion
* @param bool $parent _end identifies whether the parent category is the last
*/
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. = ' &nbsp;&nbsp; ';
}

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 sub Category array
* @param int $root
*/
function Getchild ($root = 0) {

$a = $child = Array ();
foreach ($this->arr as $id => $a) {
if ($a [' parentid '] = = $root) {
$child [$a [' id ']] = $a;
}
}
Return $child? $child: false;

}
/**
* Set Source Array
* @param $arr
*/
function Setarr ($arr = Array ()) {
$this->arr = $arr;
}
}

Through a query to save the structure into an array, and then the array of recursive operation, no doubt greatly improve the efficiency of program operation
Using code is simple

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.