-2

I've created a simple PHP Array that I wish to use with a select input on a web form (the select input was previously hardcoded in the HTML). Here's the array:

$fruits = array( 
                    'fruit' => 'apple',
                    'fruit' => 'orange',
                    'vegetable' => 'potato'
        );

and here's the select input:

<label for="Food">Select the Food</label><br>



                <select id="Subdiscipline" name="Subdiscipline">
                        <option value="*">- No Selection - </option>
                        <?php 
                            $output = "";
                            $selected = false;

                        foreach($fruits as $fruit => $value) {

                             $fruit = htmlspecialchars($fruit);

                             $output .= "<option value=\"$fruit\"";

                              if ($fruit == $previousFruitSelection) {
                                  $selected = true;
                                  $output .= " selected";
                              }
                              $output .= ">$value</option>";

                        }
                        echo $output;

                            ?>
                    </select>

The problem now that I'm no longer hardcoding the options for the select menu is that the option for 'apple' no longer appears, presumably because you can't have duplicate keys in the array. Is there a way around this to use PHP to create an array that is used to drive the select options but allow for multiple options with the same 'value=fruit'?

4

2 回答 2

2

您可以使用多维数组:

    $fruits = array( 
                'fruit' => array ('apple', 'orange')
                'vegetable' => array ('potato')
    );

Ofc 您也必须更改循环并遍历内部数组。

keys 必须是独一无二的;)

于 2013-05-26T13:32:01.347 回答
1

PHP数组是一个简单的关联数组。它将键与值匹配,因此数组中不能有 2 个水果,因为键的点是唯一的,以便能够识别数组中的某个元素。

然而,有多种方法可以解决这个问题。想到的最简单的方法是制作 2 个数组,一个用于“键”,一个用于“值”。所以第一个数组是水果、水果、蔬菜,第二个是苹果、橙子、土豆。

您还可以使用更复杂的数据结构,但我可能会做的是将数组分配为值。你可以这样做,数组中的数组。要准确检查它是如何在语法上完成的,请检查 php.net,更具体地检查以下链接上的示例 #6,我相信这可能会对您有所帮助: http: //php.net/manual/en/language.types。数组.php

于 2013-05-26T13:37:03.790 回答