簡體   English   中英

列出HTML SELECT中的類別和子類別

[英]Listing category and sub-categories in a HTML SELECT

我想在選擇列表(下拉列表)中顯示類別和子類別,如下圖所示。

在此輸入圖像描述

這是我在PHP中嘗試的方式:

// Fetch all the records:
while ($stmt->fetch()) {        
    $cats[$parent][$id] = $name;        
}

function displayList(&$cats, $parent, $level=0) {

    if ($parent==0) {
        foreach ($cats[$parent] as $id=>$nm) {
            displayList($cats, $id);
        }
    }
    else {
        foreach ($cats[$parent] as $id=>$nm) {
            echo "<option>$nm</option>\n";
            if (isset($cats[$id])) {
                displayList($cats, $id, $level+1);  //increment level
            }
        }
    }  
}

echo '<select>';
    displayList($cats, 0);
echo '</select>';

此代碼在我的下拉列表中顯示所有類別。 但我需要在子類別中添加一些縮進。

任何人都可以告訴你該怎么做。

謝謝。

嘗試添加"&nbsp;" 在子類別上,這是添加任意數量空格的HTML方式

function displayList(&$ cats,$ parent,$ level = 0){

if ($parent==0) {
    foreach ($cats[$parent] as $id=>$nm) {
        displayList($cats, $id);
    }
}
else {
    foreach ($cats[$parent] as $id=>$nm) {
       $space = "";
       foreach ($level){
           $space .= "&nbsp;&nbsp;";
       }
           echo "<option>".$space."$nm</option>\n";
           if (isset($cats[$id])) {
               displayList($cats, $id, $level+1);  //increment level
           }

    }
}  

}

如果你想使用optgroup試試:

// Fetch all the records:
while ($stmt->fetch()) {
    $cats[$parent][$id] = $name;
}

function displayList(&$cats, $parent, $level = 0) {

    if ($parent == 0) {
        foreach ($cats[$parent] as $id => $nm) {
            displayList($cats, $id);
        }
    } 
    else {

        foreach ($cats[$parent] as $id => $nm) {

            if (isset($cats[$id])) {
                echo "<optgroup label='$nm'>";
                displayList($cats, $id, $level + 1);
                echo "</optgroup>";
            } else {
                echo "<option>$nm</option>";
            }
        }
    }
}

echo '<select>';
displayList($cats, 0);
echo '</select>';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM