简体   繁体   English

在 PHP 和 MYSQLi 中以树状结构显示类别和子类别

[英]Displaying Category and Subcategory in Tree Structure in PHP and MYSQLi

I am trying to display Category and Sub Category in Tree Structure as if I click on the Category then I can get multiple Subcategory associated with that Category.我试图在树结构中显示类别和子类别,就好像我单击类别然后我可以获得与该类别关联的多个子类别。

I know this question asked multiple times but I found the answers unclear in all the questions asked previously.我知道这个问题被问了多次,但我发现之前问的所有问题的答案都不清楚。

I have created a table as:我创建了一个表:

category : cat_id  , catName
subcategory : id , cat_id , subCatName

I want to display all the category and when the user click on category then the subcategory should be listed.我想显示所有类别,当用户单击类别时,应列出子类别。 How can I do that?我怎样才能做到这一点?

<?php
  $db = new mysqli('localhost','user','password','dbname');
  $query = "SELECT id,cat FROM category";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['cat_id'], "val" => $row['cat']);
  }

  $query = "SELECT id, cat_id, subcat FROM subcategory";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $subcategories[$row['cat_id']][] = array("id" => $row['id'], "val" => $row['subcat']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcategories);


?>

<!docytpe html>
<html>

  <head>
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcategories = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("categoriesSelect");
        select.onchange = updateSubCats;
        for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);          
        }
      }
      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("subcatsSelect");
        subcatSelect.options.length = 0; //delete all options if any present
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val,subcategories[catid][i].id);
        }
      }
    </script>

  </head>

  <body onload='loadCategories()'>
    <select id='categoriesSelect'>
    </select>

    <select id='subcatsSelect'>
    </select>
  </body>
</html>

Is this what you are looking for?这是你想要的? Doesn't do a tree structure, but you could easily change the dropdowns.不做树结构,但您可以轻松更改下拉菜单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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