从php数组实现2个选择框

时间:2017-04-07 19:41:33

标签: php jquery html ajax

我有这样的php数组..

$food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday"));

我必须定义两个选择框。第一个选择框我必须选择一个类别。在第二个选择框中,我需要获取子类别的值。我该如何实施?

3 个答案:

答案 0 :(得分:0)

一种方法是打印带有蔬菜,饼干和水果的主select。接下来,您应该将其子列表打印为选择。然后,您可以使用jQuery来维护哪些应该是可见的:

<?php

$food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday"));


echo "<select id='main'>";
foreach ($food as $key => $value) {
    echo "<option value='$key'>$key</option>";
}
echo "</select>";

foreach ($food as $key => $value) {
    echo "<select class='sublist' id='$key'>";
    foreach ($value as $item) {
        echo "<option value='$item'>$item</option>";
    }
    echo "</select>";
}

?>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

$("#main").change(function () {
    $(".sublist").hide();
    $("#" + $(this).val()).show();
});
$("#main").trigger("change");
</script>

直播版:

http://neil.computer/stack/ex1.php

答案 1 :(得分:0)

仅使用 PHP

$food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday"));
$out = "";
foreach($food as $k => $v) {
    $out .= '<select name="'.$k.'">';
    foreach($v as $value) {
        $out .= '<option value="'.$value.'">'.$value.'</option>';
    }
    $out .= '</select>';
}
echo $out;
// output
<select name="Fruits">
<option value="apple">apple</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<select name="vegies">
<option value="capsicum">capsicum</option>
<option value="betroot">betroot</option>
<option value="raddish">raddish</option>
</select>
<select name="bisucuits">
<option value="marygold">marygold</option>
<option value="britania">britania</option>
<option value="goodday">goodday</option>
</select>

Sandbox

上查看

修改 - 使用array_walk

的结果相同
array_walk($food, function($v,$k) {
    echo '<select name="'.$k.'">';
    array_walk($v, function($value,$key) {
        echo '<option value="'.$value.'">'.$value.'</option>';
    });
   echo '</select>'; 
});

答案 2 :(得分:0)

我在手机上写了这个。为错误道歉。

$food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday"));

echo "<select name='myFood'>";
foreach ($food as $cat)
{
    echo "<optgroup label='$cat'>";
    foreach ($cat as $foodVal)
    {
         echo "<option value='$foodVal'>$foodVal</option>";
    }
    echo "</optgroup>";
}
echo "</select>";

实际上,为每个使用两组将允许您正确地通过多维数组。

optgroup将在select

中创建标题