【问题标题】:Multi-select add selected attribute if the value is present in the main array - php如果值存在于主数组中,则多选添加选定属性 - php
【发布时间】:2017-02-08 12:53:57
【问题描述】:

我正在使用多选和 GET 方法。我希望在基于 url 参数中的 $_GET 方法提交后重新加载表单时选择多个选项。我关联的 URL 参数是 cuisine%5B%5D=indian&cuisine%5B%5D=thai。实际上是多选择大约是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>

但问题是每个选项都被选中。实际上共有3 cuisines : indian, thai &amp; chainese2 of them are selected -> indian and thai。但问题是选择了3 个选项。 :/

【问题讨论】:

    标签: php wordpress array-intersect


    【解决方案1】:

    请记住,当您使用 array_intersect 时,它设置为 true 是两个数组中至少有一个匹配项。所以一切都被选中了。您可以试试这个:

    <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>';
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 2020-09-11
      • 2016-09-04
      • 2023-02-01
      • 2021-10-20
      • 2017-05-17
      • 1970-01-01
      • 2019-08-19
      相关资源
      最近更新 更多