使用foreach循环将数组回显到下拉列表中



我有一个2d数组,我想显示3个不同的下拉菜单。

我有数组:

$productPrices['yamaha']['French Horn'] = 2175.00;
$productPrices['yamaha']['Trumpet'] = 595.00;
$productPrices['yamaha']['Trombone'] = 775.00;
$productPrices['yamaha']['Tuba'] = 3807.00;
$productPrices['selmer']['Clarinet'] = 670.00;
$productPrices['selmer']['Oboe'] = 1999.00;
$productPrices['selmer']['Basoon'] = 7475.00; 
$productPrices['selmer']['Bass Clarinet'] = 2425.00;
$productPrices['cannonball']['Alto Saxophone'] = 2699.00;
$productPrices['cannonball']['Tenor Saxophone'] = 3197.00;  
$productPrices['cannonball']['Baritone Saxophone'] = 3964.00;
$productPrices['cannonball']['Soprano Saxophone'] = 2699.00;
$submit = "View Selection";
这是我的Foreach循环:
<?php
    echo "<h2>Product List</h2>";
    echo "<form action='catalog.php' method='post'>";
    foreach($productPrices as $category) {
        foreach($category as $product) {
            ...

这是响应它的代码,但我不确定如何使它多维:

        ...
        foreach ($category as $select => $option) {
            echo "<option value='$product'>$option</option>";
        }
        echo "</select></div>";
        }
    }
    echo "<div id='submit'><input type='submit' value='$submit'></div></form>";
?>

我调整了你的代码,使其按预期工作…看一下:

$submit = "View Selection";
echo "<h2>Product List</h2>";
echo "<form action='catalog.php' method='post'>";
foreach($productPrices as $category)
{
    echo "<div><select>";
    foreach($category as $select => $option)
    {
       echo "<option value='$option'>$select</option>";
    }
    echo "</select></div>";
}
echo "<div id='submit'><input type='submit' value='$submit'></div></form>";

上网试试

顺便说一句,我强烈建议你改进你的代码,例如从逻辑中解耦视图,而不是硬编码那么多…

相关内容

  • 没有找到相关文章