简体   繁体   中英

“self-referencing” table and arrays

MySQL table:

categoryID  
categoryName  
categoryParent

Every category has ONE parent category, though it can be NULL, which I treat as the root-category.

I want to get all categories from the table, store it in an array and print it in a way, that shows the nesting.

Example:

ID  name    parent  
1   a       NULL  
2   b       NULL  
3   c       NULL  
4   b1      2  
5   d       NULL  
6   b2      2 

HTML:

a  
b  
-b1  
-b2  
c  
d  

Later I'll try to make it draggable with jQuery so the user can choose the parent/child category by him-/herself.

Can I do all this with one single table or do I need an external junction table?

Your table structure is fine.

You'll render the nesting when you deal with the results; perhaps you loop through each result with no parent and append to the DOM, then loop through each result with a parent appending to existing elements. That only works for a two-level tree, but you get the idea.

Yes you can, just select all the rows from table. And using php, you can generate a good html table using a for loop. When you see an element with a parent, just process the table string you are constructing in your php script. From there using JQuery you can change the orders and parent child relationship of the table.

You can nest arrays and have a structure like (Array of (me, childrenArray)). That way you use the "me" for indexing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM