我在获取类别和子类别时遇到了麻烦

时间:2010-11-10 19:12:14

标签: 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 = 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>

让我试着解释我遇到的问题。我认为我的整个设计都不合适,因为它感觉就像那样,但我现在有脑筋。

在函数中我返回一个像Array ( [0] => Array ( [1] => Computers ) [1] => Array ( [4] => Music ) )这样的数组。如果您认为这是错误的退货方式,请告诉我。好的,你看到CategoriesMain了吗?我正在使用for循环来输出此数组,而option=value im echoing $i但是这个$ i就像1, 2, 3, 4但是我希望该值是父类别的值,例如1, 4以便我可以在下一个for循环中使用$_POST['cateogoriesMain']收集值,我将显示cateogriesSub,以便为之前为parent_id = to whatever was selected in the selectbox的用户获取数据库行。我希望这是有道理的。

1 个答案:

答案 0 :(得分:1)

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

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

编辑也会更改php函数中的以下行,而不是:

array_push($categories, array($row['id'] => $row['name']));

DO

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