繁体   English   中英

在选择选项中显示每个类别及其项目

[英]display each category with their items from table in select option

我有一张桌子products_tbl

+----------+-----------+---------------+
|product_id|ProductName|ProductCategory|
+----------+-----------+---------------+
|1         |Apple      |fruits         |
|2         |Orange     |fruits         |
|3         |Iphone X   |Electronics    |
|4         |FJ-Eye Lens|Accessories    |
+----------+-----------+---------------+

我想使用HTML SELECT OPTION在分隔组中显示每个类别项目

产品.php

$productQ = "SELECT * FROM products_tbl ";
try { 
    $stmt2 = $db->prepare($productQ); 
    $stmt2->execute();
} catch(PDOException $ex) {   
    die("Failed to run Query: " . $ex->getMessage()); 
} 

$produtsrows = $stmt2->fetchAll(); 

echo"<select>";
foreach($produtsrows as $prow): 
    echo "<optgroup label=".$prow['ProductCategory'].">";
    echo"   <option>".$prow['ProductName']."</option>
          </optgroup>";
endforeach;
echo "
    </select>
    ";

它像这样显示

fruits
Apple 
fruits
Orange  
Electronics    
Iphone X
Accessories    
FJ-Eye Lens

您需要更改 foreach 循环以在与上一个相同时不输出类别名称:

$last_cat = "";
foreach($produtsrows as $prow): 
    if (($cat = $prow['ProductCategory']) != $last_cat) {
        if ($last_cat != "") echo "</optgroup>\n";
        echo '<optgroup label="'.$cat.'">' . "\n";
        $last_cat = $cat;
    }
    echo"   <option>".$prow['ProductName']."</option>\n";
endforeach;
echo "</optgroup>\n";   

输出(用于您的数据)

<optgroup label="fruits">
   <option>Apple</option>
   <option>Orange</option>
</optgroup>
<optgroup label="Electronics">
   <option>Iphone X</option>
</optgroup>
<optgroup label="Accessories">
   <option>FJ-Eye Lens</option>
</optgroup>

我稍微改变了你的代码:

$productQ = "SELECT * FROM products_tbl ORDER BY ProductCategory ASC";
try { 
    $stmt2 = $db->prepare($productQ); 
    $stmt2->execute();
} catch(PDOException $ex) {   
    die("Failed to run Query: " . $ex->getMessage()); 
} 

$produtsrows = $stmt2->fetchAll(); 

echo"<select>";
$category = "";
foreach($produtsrows as $prow): 
    if ($category != $prow['ProductCategory']) {
        if ($category != "") {
            echo "</optgroup>";
        }
        $category = $prow['ProductCategory'];
        echo "<optgroup label=".$prow['ProductName'].">";
    }
    echo"   <option>".$prow['ProductName']."</option>
endforeach;
echo "</optgroup>
    </select>
    ";

首先请注意,我添加了ORDER BY ProductCategory ASC以确保具有相同类别的所有产品始终在一起。

接下来我只在类别与上一项不同时添加<optgroup>标签。

请注意,我假设所有产品都有一个有效的类别。 如果您的类别为空,则生成的 html 将会混乱。

暂无
暂无

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

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