PHP: An algorithm for tree-shaped structures

Source: Internet
Author: User

From the joy of the village reprinted, before also read this article, the narrative is still relatively clear.

Product classification, multi-level tree structure of the forum, mailing lists and many other places we all encounter this problem: how to store multi-level structure of data?

In the PHP (PHP training PHP Tutorial) application, providing back-end data storage is usually a relational database, it can save a lot of data, provide efficient data retrieval and update Services. However, the basic form of relational data is a criss-cross table, and it is a planar structure, so if we want to store the multilevel tree structure in the relational database, we need to make a reasonable translation work. Next I will see what I saw and some practical experience and everyone to explore.

There are basically two common design methods for hierarchical data storage in a flat database:

Adjacent directory mode (adjacency list model)

Pre-sorted traversal tree algorithm (modified preorder tree traversal algorithm)

I am not a computer professional, and have not learned anything about data structure, so these two names are my own in accordance with the literal meaning of flipping, if wrong, please give more advice.

These two things sound like scary, but it's very easy to understand. Here I use a simple food catalogue as our sample data. Our data structure is this:

Food

|

|---Fruit

| |

| |---Red

| | |

| | | |--cherry

| |

| |---Yellow

| |

| |--banana

|

|---meat

|

|--beef

|

|--pork

In order to take care of those English mess PHP enthusiasts

Food: Foods

Fruit: Fruit

Red: Pink

Cherry: Cherry

Yellow: Yellow

Banana: Banana

Meat: Meat

Beef: Beef

Pork: Pork

PHP: An algorithm for tree-shaped structures

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.