Multi-select 添加 selected 属性,如果该值存在于主数组中 - php

Multi-select add selected attribute if the value is present in the main array - php

我正在使用 multi-select 并且 GET method.I 需要多个选项 select 在提交后根据 [=29 的 $_GET 方法重新加载表单时编辑=] parametres.i 关联的 URL 参数是 cuisine%5B%5D=indian&cuisine%5B%5D=thai。实际上 multi-select 是关于 cuisine

我的代码如下:

 <select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
    <?php
        $selected_cuisine = $_GET['cuisine'];
        // Get all cuisines list by get_terms() function.Its built in wordpress
        $restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
        $cuisines = array();
        foreach ($restaurant_cuisines as $restaurant_cuisine) {
            // echo $restaurant_cuisine;
            array_push( $cuisines, $restaurant_cuisine->slug );
            // echo $cuisines_list;
        }
        print_r ($selected_cuisine);
        print_r($cuisines);
        if(array_intersect($selected_cuisine, $cuisines)){
            $selected = 'selected';
        }else{
            $selected = '';
        }
        foreach ($restaurant_cuisines as $cuisine) {
            echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
        }
    ?>
</select>

但问题是每个选项都得到 selected.Actually 总共 3 cuisines : indian, thai & chainese2 of them are selected -> indian and thai。但问题是 3 个选项是 select编辑。 :/

请记住,当您使用 array_intersect 时,它设置为 true 在两者中至少有一个匹配 array.So 一切都得到 selected.Rather 你可以试试这个:

<select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
<?php
    $selected_cuisine = $_GET['cuisine'];
    // Get all cuisines list by get_terms() function.Its built in wordpress
    $restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
    $cuisines = array();
    foreach ($restaurant_cuisines as $restaurant_cuisine) {
        array_push( $cuisines, $restaurant_cuisine->slug );
    }
    foreach ($restaurant_cuisines as $cuisine) {
        if(in_array($cuisine->slug, $selected_cuisine)){
          $selected = 'selected';
        }else{
          $selected = '';
        }
        echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
    }
?>