从嵌套数组中选择下拉菜单

时间:2019-02-15 11:21:10

标签: javascript php jquery

我有嵌套数组(3d),想使用PHPjQuery

将其值放在下拉选择菜单中

我做了一些尝试,但仅适用于两个级别的数组,例如(类别,子类别),但是如果每个或某些子类别也具有更多的子分区又怎么办,这是一个例子

$categories = array(
    'fruits' => array(
        'red' => array('one', 'two', 'three'),
        'yellow' => array('four', 'five', 'six'),
        'black' => array('seven', 'eight', 'nein'),
    ),
    'vegetables' => array(
        'blue' => array('een', 'twee', 'drie'),
        'white' => array('vier', 'funf', 'zex'),
        'mongo' => array('zibn', 'acht', 'noun'),
    )
);

我要做的是显示主要类别(fruits,vegetables)

<select name="food">
    <?php foreach ($categories as $category): ?>
        <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
    <?php endforeach;?>
</select>

在选择(change)时,任何一个都会显示我选择的类别的子类别的选择选项。

,然后在选择任何子类别时,它将显示其子子类别。

Image explain more

1 个答案:

答案 0 :(得分:1)

可以这样做

$categories = array(
    'fruits' => array(
        'red' => array('one', 'two', 'three'),
        'yellow' => array('four', 'five', 'six'),
        'black' => array('seven', 'eight', 'nein'),
    ),
    'vegtiable' => array(
        'blue' => array('een', 'twee', 'drie'),
        'white' => array('vier', 'funf', 'zex'),
        'mongo' => array('zibn', 'acht', 'noun'),
    )
);

// Funtion to generate select box (using single or multi-dimensional array)
function create_select($categories,$level=1,$parrent=''){
    $second_select = '';
    $select = '<select name="category" class="category '.($parrent ? $parrent : '').'" '.($parrent ? 'style="display:none;"' : '').' data-category-level="'.$level.'">';
    // loop through category
    foreach ($categories as $key => $cat) {
        if(is_array($cat)){
            $select .= '<option value="'.$key.'">'.$key.'</option>';
            // if it has sub-category then generate sub-select 
            $second_select .= create_select($cat,$level+1,$key);
        }else{
            $select .= '<option value="'.$cat.'">'.$cat.'</option>';
        }
    }
    // append sub-select to select
    $select .= '</select>'.$second_select;
    return $select;
}

print_r(create_select($categories));
?>

您将需要以下脚本来显示和隐藏子选择

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
    $('.category').on('change',function(){
        var thisp = $(this);
        $('.category').each(function(){
            // check if it is sub-select of current select (using category-level)
            if($(this).data('category-level') > thisp.data('category-level')){
                if($(this).hasClass(thisp.val())){
                    // show only sub-select that has matching class
                    $(this).css('display','block');
                }else{
                    // hide all other sub-select
                    $(this).css('display','none');
                }
            }
        });
    });

</script>