Php I';我在获取类别和子类别时遇到困难

Php I';我在获取类别和子类别时遇到困难,php,sql,oop,function,recursion,Php,Sql,Oop,Function,Recursion,这是我的数据库: id name parent_id 1 Computers NULL 2 Apple 1 3 Books 1 4 Music NULL 5 CDs 4 6 Records 4 我的类别功能: public function showCategories($parent_id

这是我的数据库:

id         name       parent_id

1          Computers   NULL
2          Apple       1
3          Books       1
4          Music       NULL
5          CDs         4
6          Records     4
我的类别功能:

 public function showCategories($parent_id = 0){
        if($parent_id == 0){
            $sql = "SELECT * FROM categories WHERE parent_id IS NULL";
        } else {
            $sql = "SELECT * FROM categories WHERE parent_id =:parentid";
        }

        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':parentid', $parent_id);
        $stmt->execute();

        $categories = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            array_push($categories, array($row['id'] => $row['name']));
        }
        return $categories;
    }
这是我的分类页面:

<?php
//Instantiate categories class
$categories = new categories($db);
$categoriesMain = $categories->showCategories(0);
?>
<html>
   <head></head>
   <body>
       <form action="" method="post">
           <?php //Get parent categories and put them into a select box ?>
           <select name="categoriesMain">
                <?php for($i=0;$i<count($categoriesMain);$i++){ ?>
                      <option value="<?php echo $i; ?>">
                           <?php echo $categoriesMain[$i]; ?>
                      </option>
                <?php } ?>
           </select>
       <input type="submit" name="submit" value="submit"/>
       </form>

       <?php //if form submits then show sub categories ?>
          <?php if(isset($_POST['submit'])){
                    $categoriesSub = $categories->showCategories($_POST['categoriesMain']);
                    for($i=0;$i<count($categoriesSub);$i++){
                        echo $categoriesSub[$i];
                    }
          } ?>
    </body>
</html>


您应该使用数组的键作为选项值,如下所示:

   <select name="categoriesMain">
            <?php foreach ($categoriesMain as $k => $v) { ?>
                  <option value="<?php echo $k; ?>">
                       <?php echo $v; ?>
                  </option>
            <?php } ?>
   </select>


您应该使用数组的键作为选项值,如下所示:

   <select name="categoriesMain">
            <?php foreach ($categoriesMain as $k => $v) { ?>
                  <option value="<?php echo $k; ?>">
                       <?php echo $v; ?>
                  </option>
            <?php } ?>
   </select>

$categories[$row['id']] = $row['name'];