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

时间:2015-07-17 20:19:42

标签: php arrays multidimensional-array foreach

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

我有阵列:

man qconf

这是我的Foreach循环:

$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";

这是回应它的代码,但我不知道如何使它成为多维的:

<?php
    echo "<h2>Product List</h2>";
    echo "<form action='catalog.php' method='post'>";
    foreach($productPrices as $category) {
        foreach($category as $product) {
            ...

1 个答案:

答案 0 :(得分:2)

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

$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>";

Try it online

BTW我强烈建议你改进代码,例如将视图与逻辑分离,而不是如此多地编码......