Php + mysql unlimited classification instance (non-recursive) _ php instance without Recursion

Source: Internet
Author: User
This article mainly introduces php + mysql unlimited classification instances that do not require recursion, with a focus on non-recursion. For more information, see How to Implement unlimited classification, recursion is generally the first and easiest way to think of, but recursion is generally considered a resource-consuming method, so many systems do not consider using recursion.
This article uses the database design and an SQL statement to implement
The database fields are roughly as follows:

The Code is as follows:

Id
Fid parent category ID
Class_name category name
Path classifier path, which uses id as a node to form a string similar to, 1, 2, 3, and 4.

Assume that the following data is available:

The Code is as follows:


Id fid class_name path
1 0 Category 1, 1,
2 0 Category 2, 2,
3 1 Classification 1-1, 1, 3,
4 1 Classification 1-2, 1, 4,
5 2 categories 2-1, 2, 5,
6 4 categories 1-2-1, 1, 4, 6,

Unlimited 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_count ($ rows ['path'], ',')-2); $ I ++) echo '';} echo $ rows ['class _ name'].'
';}?> $ 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) {/*** first Display Method * // * $ space = str_repeat ('', count (explode ('-', $ row ['abspath'])-1); echo $ space. $ row ['name']. ''; * // ** second Display Method */$ space = str_repeat ('--', count (explode ('-', $ row ['abspath']) -1); $ option. = ''. $ space. $ row ['name'].'
';} Echo $ option; exit (); echo''. $ Option .'';

$ Nbs is a database operation class. This method is simple and clear!

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.