There are roughly three ways to type PHP's infinite categories,
1, the database by setting the parent class ID to make a unique index, and then use the function of recursive calls to achieve an infinite classification;
2, database design through a specific format, and then use MySQL query key functions: Concat. Program implementation is relatively simple;
3, the third is not too understanding, as if to use the algorithm and data structure to arrange.
Today, I mainly share the second way, I also found a lot of information at the beginning, it is really difficult to understand. But finally to understand, so write down essays, hope that through this article can help everyone.
First, the database design:
Copy Code code as follows:
--
--Table structure for table ' category '
--
CREATE TABLE IF not EXISTS ' category ' (
' id ' int (one) not NULL auto_increment,
' Catpath ' varchar (255) DEFAULT NULL,
' Name ' varchar (255) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT Charset=utf8 auto_increment=11;
--
--Dumping data for table ' category '
--
INSERT into ' category ' (' id ', ' catpath ', ' name ') VALUES
(1, ' 0 ', ' website Home '),
(2, ' 0-1 ', ' Linux OS '),
(3, ' 0-1 ', ' Apache server '),
(4, ' 0-1 ', ' MySQL database '),
(5, ' 0-1 ', ' PHP scripting language '),
(6, ' 0-1-2 ', ' Linux system Tutorial '),
(7, ' 0-1-2 ', ' Linux Network technology '),
(8, ' 0-1-2 ', ' Linux Security Basics '),
(9, ' 0-1-2-7 ', ' Linux LAMP '),
(' 0-1-3-10 ', ' Apache Server ');
In this note, the Catpath-link symbol is not fixed, you can choose, such as special symbols.
Second, the PHP code implementation:
Copy Code code as follows:
$conn = mysql_connect (' localhost ', ' root ', ');
mysql_select_db (' Test ', $conn);
mysql_query (' Set names UTF8 ');
$sql = "Select Id,concat (Catpath, '-', id) as Abspath,name from category order by Abspath";
$query = mysql_query ($sql);
while ($row = Mysql_fetch_array ($query)) {
/**
* The first method of presentation
*/
/* $space = Str_repeat (', Count (Explode ('-', $row [' Abspath '])-1);
Echo $space. $row [' name ']. ' <br> ';
/**
* The second method of presentation
*/
$space = Str_repeat ('), Count (Explode ('-', $row [' Abspath '])-1);
$option. = ' <option value= '. $row [' id ']. ' > '. $space. $row [' name ']. ' </option> ';
}
Echo ' <select name= ' opt ' > '. $option. ' </select> ';
On the effect chart:
Here are a few key points to note:
1, in the database query field is using the Concat function, do not know where Google can be.
2, the second place is mainly used in PHP str_repeat cleverly set the space.
There are mistakes, look mail:chenghuiyong1987@gmail.com or leave a message