简体   繁体   中英

Unlimited depth category, sub-category

I am trying to implement an unlimited depth category, subcategory section in my web site. I am really confused about this. The table structure is

id                medium int  auto incrimant , primary
name              varchar
parent            medium int

I am looking for the solution of the following problems:

  1. How can I write the code to allow the user to enter unlimited category, sub-category?
  2. How can I load the category, sub-category in a tree order inside a select box?

Using MPTT, you will need to change your table structure a little for use MPTT. But it's an infinite way to make unlimited depth.

Source: http://waliaz.com/modified-pre-ordered-traversal-tree-mptt---explained.html

You can create an array and recursively build the tree:

$q = mysql_query("SELECT id, parent_id, name FROM categories");
while ($r = mysql_fetch_row($q)) {
  $names[$r[0]] = $r[2];
  $children[$r[0]][] = $r[1];
 }

function render_select($root=0, $level=-1) {
  global $names, $children;
  if ($root != 0)
    echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
  foreach ($children[$root] as $child)
    render_select($child, $level+1);
}

echo '<select>';
render_select();
echo '</select>';
  1. More efficient hierarchy system

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