我有以下PHP代码
$selected_items = explode(',' , $vars['value']);
foreach($vars['options'] as $option) {
$selected = "";
if(in_array($option,$selected_items)){
$selected = " selected = 'selected'";
}
echo "<option" . $selected . ">" . $option . "</option>";
}
$selected_items:
array
0 => string 'Html' (length=4)
1 => string ' Css' (length=4)
2 => string ' HTML5' (length=6)
3 => string ' CSS3' (length=5)
4 => string ' Javascript' (length=11)
$vars['options']:
array
0 => string 'Html' (length=4)
1 => string 'Css' (length=3)
2 => string 'HTML5' (length=5)
3 => string 'CSS3' (length=4)
4 => string 'Javascript' (length=10)
5 => string 'Dhtml' (length=5)
6 => string 'Actionscript' (length=12)
7 => string 'Javafx' (length=6)
8 => string 'Flex' (length=4)
9 => string 'VisualBasic' (length=11)
10 => string 'Ajax' (length=4)
11 => string 'ASP.NET' (length=7)
12 => string 'Java' (length=4)
13 => string 'Php' (length=3)
14 => string 'Perl' (length=4)
15 => string 'Python' (length=6)
16 => string 'J2ME' (length=4)
17 => string 'VB.NET' (length=6)
18 => string 'C#' (length=2)
19 => string 'ASP' (length=3)
20 => string 'JSP' (length=3)
21 => string 'J2EE' (length=4)
22 => string 'C++' (length=3)
在$selected_items
中有一个数组。所以我必须检查$option
中的值是否在$selected_items
中。但它第一次工作。但第二次该值在数组中但条件变为false。
知道问题在哪里?
答案 0 :(得分:1)
如果该字符串存在于数组中,它应该可以工作。 如果您对上述问题有疑问,可以试试这个:
$selected_items = explode(',' , $vars['value']);
foreach($vars['options'] as $option) {
$selected = "";
foreach($selected_items as $selecteditems){
if($option == $selecteditems)){
$selected = " selected = 'selected'";
}}
echo "<option" . $selected . ">" . $option . "</option>";
}
答案 1 :(得分:0)
只需删除数组$selected_items
中字符串前的空格。