简体   繁体   English

如何在选择列表中显示类别,子类别,子子类别 - php / mysql?

[英]How to display categories, subcategories, sub-subcategories in select list - php/mysql?

I want to display categories, subcategories and sub-subcategories in a select list (drop-down list) like the way the WordPress shows in its admin panel. 我想在选择列表(下拉列表)中显示类别,子类别和子子类别,就像WordPress在其管理面板中显示的方式一样。 First look at my database table (tb_categories) - 首先看看我的数据库表(tb_categories) -

数据库表

I want the following output in HTML form - 我想要HTML格式的以下输出 -

产量

The two items "None" and "Uncategorized" are hardcoded in the code. “无”和“未分类”这两个项目在代码中是硬编码的。 I am wondering how to display categories and their subcategories in hierarchical order using select list options. 我想知道如何使用选择列表选项按层次顺序显示类别及其子类别。

I am trying with the following sql query in which I am using self join. 我正在尝试使用以下sql查询,其中我使用自联接。 Here it is - 这里是 -

SELECT
    `cat`.`category_name` AS 'category name',
    `cat2`.`category_name` AS 'parent category'
FROM
    `tb_categories` AS `cat`
LEFT JOIN `tb_categories` AS `cat2` ON `cat`.`category_parent` = `cat2`.`category_id`
ORDER BY
    'parent category'

And the output it is giving is - 它给出的输出是 -

Array
(
    [0] => Array
        (
            [0] => My Parent Category
            [category name] => My Parent Category
            [1] => 
            [parent category] => 
        )

    [1] => Array
        (
            [0] => Parent Category 2
            [category name] => Parent Category 2
            [1] => 
            [parent category] => 
        )

    [2] => Array
        (
            [0] => Parent Category 3
            [category name] => Parent Category 3
            [1] => 
            [parent category] => 
        )

    [3] => Array
        (
            [0] => My Child Category
            [category name] => My Child Category
            [1] => My Parent Category
            [parent category] => My Parent Category
        )

    [4] => Array
        (
            [0] => Sports
            [category name] => Sports
            [1] => 
            [parent category] => 
        )

    [5] => Array
        (
            [0] => Cricket is best
            [category name] => Cricket is best
            [1] => Sports
            [parent category] => Sports
        )

    [6] => Array
        (
            [0] => AJAX
            [category name] => AJAX
            [1] => 
            [parent category] => 
        )

    [7] => Array
        (
            [0] => hockey is best
            [category name] => hockey is best
            [1] => Sports
            [parent category] => Sports
        )

)

I don't know and even not sure how can I display above data in that select list. 我不知道甚至不确定如何在该选择列表中显示上述数据。 How we do that? 我们怎么做? How can we do it using joins? 我们怎样才能使用连接呢? If we use joins then do we need some array to store and sort the results? 如果我们使用连接,那么我们是否需要一些数组来存储和排序结果? And also how do we do it using several queries in a loop? 还有我们如何在循环中使用多个查询来做到这一点? Which method will be best? 哪种方法最好?

Assuming your given array is in $array you can use this. 假设您的给定数组在$ array中,您可以使用它。 But as I told you already you should select the ids to handle categories with the same name and to use them as option values in your selectbox: 但正如我告诉你的那样,你应该选择id来处理具有相同名称的类别,并将它们用作选择框中的选项值:

  $options = get_options($array);
  echo "<select>";
  foreach($options as $val) {
    echo "<option>".$val."</option>";
  }
  echo "</select>";

  function get_options($array, $parent="", $indent="") {
    $return = array();
    foreach($array as $key => $val) {
      if($val["parent category"] == $parent) {
        $return[] = $indent.$val["category name"];
        $return = array_merge($return, get_options($array, $val["category name"], $indent."&nbsp;&nbsp;&nbsp;"));
      }
    }
    return $return;
  }

Assuming that you now have the ids in your array as "category_id" and "parent_category_id" you can use this. 假设您现在将数组中的ID设置为“category_id”和“parent_category_id”,则可以使用此选项。 The "x" prior to the key in $return is just to avoid that php changes your keys, because they are numeric. 在$ return中键之前的“x”只是为了避免php更改你的键,因为它们是数字的。

  $options = get_options($array);
  echo "<select>";
  foreach($options as $key => $val) {
    echo "<option value='".substr($key,1)."'>".$val."</option>";
  }
  echo "</select>";

  function get_options($array, $parent=0, $indent="") {
    $return = array();
    foreach($array as $key => $val) {
      if($val["parent_category_id"] == $parent) {
        $return["x".$val["category_id"]] = $indent.$val["category name"];
        $return = array_merge($return, get_options($array, $val["category_id"], $indent."&nbsp;&nbsp;&nbsp;"));
      }
    }
    return $return;
  }

This is the simplest category table structure 这是最简单的类别表结构

+-------------------------+
| categories              |
+-------------------------+
| category_id   (int)     | PK
| parent_id     (int)     | Index
| category_name (varchar) |
| ...                     |
+-------------------------+

The function below will recursively fetch all categories and build a hierarchy. 下面的函数将递归地获取所有类别并构建层次结构。 As you may see, you can choose a value to be preselected or you can fetch only a part of the hierarchy changing parent value. 如您所见,您可以选择要预先选择的值,也可以仅获取更改父级值的层次结构的一部分。

function build_category_tree(&$output, $preselected, $parent=0, $indent=""){
  $r = mysql_query("
    SELECT category_id, category_name FROM categories WHERE parent_id = " . $parent . "
  ");

  while($c = mysql_fetch_array($r, MYSQL_ASSOC)){
    $selected = ($c["category_id"] == $preselected) ? "selected=\"selected\"" : "";
    $output .= "<option value=\"" . $c["category_id"] . "\" " . $selected . ">" . $indent . $c["category_name"] . "</option>";
    if($c["category_id"] != $parent){
      build_category_tree($output, $preselected, $c["category_id"], $indent . "&nbsp;&nbsp;");
    }
  }
}

Usage: 用法:

<?php 
build_category_tree($categories, 0); 
// if you want to preselect a value and start from some subcategory
build_category_tree($categories, 5, 2); 
?>

<!-- HTML -->
<select><?php echo $categories ?></select>
<!-- if you want to add some extra options -->
<select>
  <option value="-1">Choose a category</option> 
  <?php echo $categories ?>
</select>

Side note: Although this function looks elegant, do not use it if you have thousands of categories. 附注:虽然此功能看起来很优雅,但如果您有数千个类别,请不要使用它。 Also, use MySQLi or PDO_MySQL extension in your final version. 此外,在最终版本中使用MySQLi或PDO_MySQL扩展。

Database View For Categories 数据库视图的类别

$con = mysqli_connect("localhost","root","","categories"); 
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT `cat`.`categoryName` AS 'category name', `cat2`.`categoryName` AS 'parent category' FROM `product_category` AS `cat` LEFT JOIN `product_category` AS `cat2` ON `cat`.`parentId` = `cat2`.`categoryId` where `cat2`.`categoryName` !='NULL' order by `cat2`.`categoryName`");

  while($res=mysqli_fetch_array($sql,MYSQLI_ASSOC)){
  $cat[] = $res['category name'];
  $parent[]= $res['parent category'];
}
$parents = "";
for($i=0;$i<count($cat);$i++){
 if($parents!=$parent[$i]){
if($i!=0){ echo "</ul>"; }
 echo $parent[$i]."<ul><li>".$cat[$i]."</li>" ;
}else{

 echo "<li>".$cat[$i]."</li>" ;
}
$parents = $parent[$i];
}
echo "</ul>";

Output 产量

Form More tutorials regarding php, ajax, jquery, mysql, interview questions. 表格更多有关php,ajax,jquery,mysql,面试问题的教程。 kindly see my blogs hackandphp.com 请看我的博客hackandphp.com

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

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