我正在使用多选择和GET方法。我希望在提交后根据url parametres.i中的$ _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 & chainese
和2 of them are selected
- &gt; indian and thai
。但问题是选择了3个选项。 :/
答案 0 :(得分:0)
请记住,当您使用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>';
}
?>