【问题标题】:How to list parent categories in dropdown?如何在下拉列表中列出父类别?
【发布时间】:2019-03-29 16:38:29
【问题描述】:

我有一个在option 框中列出类别的功能,但我想在下拉列表中列出类别以进行导航。

我可以列出主要类别,但无法列出父类别。

任何帮助将不胜感激。谢谢

这是我的功能:

function categori($parent_id = 0, $st = 0){
  Global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE parent_id = :parent");
    $stmt->execute(array('parent'=>$parent_id));
    $v = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $say = $stm

t->rowCount();
     if($say){
        foreach($v as $rows){
         echo "<li><a href=".$rows['cat_id']."/".$rows['seo_url'].">".$rows['cat_name']."</a></li>";
                       categori($rows['cat_id']);
                }
            }
     unset($stmt);
    } 

乌萨克:

categori();

下拉菜单:

<ul>
    <li><a href="cat">main cat</a>
        <ul>
            <li><a href="cat">child cat</a></li>
        </ul>
   </li>
</ul>

【问题讨论】:

    标签: html css php-7


    【解决方案1】:

    由于您的函数categori 将父类别ID 作为参数,您可以轻松地显示父类别和子类别。

    只需稍微更改一下您的 html 模板。 首先获取主要类别。这些应该是父类别 id 为 0 的所有类别。

    <?php $parentCategories = category(); ?>
    

    然后遍历所有父类别并按父类别 id 获取子类别。

    <ul>
    <?php foreach ($parentCategories as $parentCategory) : ?>
        <li>
            <a href="cat"><?= $parentCategory['name'] ?></a>
            <ul>
            <?php
                $children = category($parentCategory['id']); 
                foreach ($children as $child) :
            ?>
                <li><?= $child['name'] ?></li>
            <?php endforeach; ?>
            </ul>
        </li>
        <?php endforeach; ?>
    </ul>
    

    如您所见,有两个foreach 迭代。第一个遍历父类别。第一个 foreach 循环中的第二个循环遍历您通过父类别 ID 获取的子类别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2021-06-21
      相关资源
      最近更新 更多