Php+mysql an infinite class instance (non-recursive) _php instance without recursive implementation

Source: Internet
Author: User

To achieve an infinite class of classification, recursion is generally the first and easiest to think of, but recursion is generally considered to occupy the resources of the method, so many systems are not considered using recursive
In this paper, through the design of the database, a SQL statement is used to implement
The database fields are probably as follows:

Copy Code code as follows:
ID number
FID parent category number
Class_name category Name
Path classification paths, with IDs as nodes, composed of similar, 1,2,3,4, strings

You can assume the following data:

Copy Code code as follows:

ID FID class_name Path
1 0 Categories 1, 1,
2 0 Categories 2, 2,
3 1 Categories 1-1, 1, 3,
4 1 Categories 1-2, 1, 4,
5 2 Categories 2-1, 2, 5,
6 4 Classification 1-2-1, 1,4,6,

Infinite Classification Operation code:

<?php $sql = "SELECT * from Tree order by path";  
$result = $nbs->query ($sql); while ($rows = $nbs->fetch_array ($result)) {if (Substr_count ($rows [' Path '], ', ') >2) {for ($i =0; $i < (Substr_cou  
  NT ($rows [' Path '], ', ')-2); $i + +) echo '; echo $rows [' class_name ']. '  
<br> ';
?> $conn = mysql_connect (' localhost ', ' root ', ' root ');
mysql_select_db (' wanggou123 ', $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 presentation method/* $space = str_repeat ('      ', COUNT (
Explode ('-', $row [' Abspath '])-1); Echo $space. $row [' name '].
'; *//** the second presentation method/$space = Str_repeat ('--', Count (Explode ('-', $row [' Abspath '])-1); $option. = ". $space. $row [' name '].
' <Br> ';
Echo $option;
Exit (); Echo ' <select name= ' opt ' > '. $option. '&Lt;/select> '; 

Where $nbs is a database operation class, this method is straightforward!

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.