PHP Infinite Class classification method and code

Source: Internet
Author: User

Whether you're building your own forums, posting messages on your site or writing your own CMS, you'll encounter situations where you want to store hierarchical data in a database. Also, unless you use a database like XML, the tables in the relational database are not hierarchical, they are just a flat list. So you have to find a way to transform a hierarchical database.

The storage tree structure is a common problem, and he has several solutions. There are two main methods: Adjacency list model and improved first order traversal tree algorithm

In this article, we'll explore these two ways to save hierarchical data. I'll give an example of an online grocery store tree. The Food store organizes food by category, color and variety. Tree is as follows:

This article contains examples of code to demonstrate how to save and retrieve data. I chose PHP to write examples, because I often use this language, and many people are using it or know it. You can easily translate them into your own language.

Adjacency list models (the adjacency list model)

The first-and most graceful-method we try is called "adjacency list Model" or "recursive method". It's a very elegant approach because you just need an easy way to iterate through your tree. In our grocery store, the table of adjacency list is as follows:

As you can see, save a "parent" node for each node. We can see that "Pear" is a child of "Green", and the latter is a child node of "Fruit", and so on. Root node, "Food", then his parent node has no value. For simplicity, I used only the "title" value to identify each node. Of course, in the actual database, you want to use the ID of the number.

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.