Select2 从服务器获取值

Select2 get value from server

我正在为多选字段使用 Select2,我从服务器获取选项,我可以将它们存储在数据库中,但我不确定如果我已经有一些选项,我该如何显示所选选项数据库中的值。

            <select name="multipleSelect2[]" class="multipleSelect2" multiple="true">
                <?php foreach ($modality_list as $term) { ?>
                     <option value="<?php echo $term->term_id ?>"><?php echo $term->name ?></option> 
                <?php } ?>
            </select> 

            <script>
               $(document).ready(function(){
                $(".multipleSelect2").select2({
                        placeholder: "select modalities.." //placeholder
                    });
                })
            </script>

dd 选项

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 38
            [name] => Biofield Tuning
            [slug] => biofield-tuning
            [term_group] => 0
            [term_taxonomy_id] => 38
            [taxonomy] => product_cat
            [description] => 
            [parent] => 92
            [count] => 3
            [filter] => raw
        )

    [1] => WP_Term Object
        (
            [term_id] => 80
            [name] => Breathwork
            [slug] => breathwork
            [term_group] => 0
            [term_taxonomy_id] => 80
            [taxonomy] => product_cat
            [description] => 
            [parent] => 92
            [count] => 1
            [filter] => raw
        )
) ....

从数据库中选择的值

["38","80"]

我找到了一个方法。如果该值存在则选择为真。

<select name="multipleSelect2[]" class="multipleSelect2" multiple="true">
    <?php foreach ($modality_list as $term) {
      if(in_array($term->term_id, $multipleSelect2)){ ?>
         <option value="<?php echo $term->term_id ?>" selected><?php echo $term->name ?></option> 
    <?php } else{?>
         <option value="<?php echo $term->term_id ?>"><?php echo $term->name ?></option> 
    <?php }} ?>
</select>