使用php根据过去的用户偏好检查复选框?

时间:2014-07-21 15:37:18

标签: php

我尝试根据以前存储在CSV中的用户首选项来检查复选框,但它只运行检查CSV中的第一个索引并跳过其余部分。在下面的代码中,如果我将其传递给"体育,低调,葡萄酒"我希望它在页面加载时检查这三个,但它只检查Sports

$typeArray = array(
            "1" => "Sports",
            "2" => "College",
            "3" => "Pub",
            "4" => "Night Club",
            "5" => "Lowkey",
            "6" => "Wine",
            "7" => "Craft Beer",
        );
        $Sports="";
        $College="";
        $Pub="";
        $NightClub="";
        $Lowkey="";
        $Wine="";
        $CraftBeer="";
        $string = "Sports, Lowkey, Wine";
        $csv = str_getcsv($string, ", ");
        for($i=0; $i<count($csv); $i++){
            $index = array_search($csv[$i], $typeArray);
            if($index == 1){
                $Sports = "checked";
            }
            if($index == 2){
                $College = "checked";
            }
            if($index == 3){
                $Pub = "checked";
            }
            if($index == 4){
                $NightClub = "checked";
            }
            if($index == 5){
                $Lowkey = "checked";
            }
            if($index == 6){
                $Wine = "checked";
            }
            if($index == 7){
                $CraftBeer = "checked";
            }
            unset($index);
        }
        echo "<input type=\"checkbox\" name=\"Type[1]\" value=\"Sports\"" . $Sports . ">Sports ";
        echo "<input type=\"checkbox\" name=\"Type[2]\" value=\"College\"" . $College . ">College ";
        echo "<input type=\"checkbox\" name=\"Type[3]\" value=\"Pub\"" . $Pub . ">Pub ";
        echo "<input type=\"checkbox\" name=\"Type[4]\" value=\"Night Club\"" . $NightClub . ">Night Club ";
        echo "<input type=\"checkbox\" name=\"Type[5]\" value=\"Lowkey\"" . $Lowkey . ">Lowkey<br> ";
        echo "<input type=\"checkbox\" name=\"Type[6]\" value=\"Wine\"" . $Wine . ">Wine ";
        echo "<input type=\"checkbox\" name=\"Type[7]\" value=\"Craft Beer\"" . $CraftBeer . ">Craft Beer<br> ";

2 个答案:

答案 0 :(得分:1)

交换这条线 $index = array_search($csv[$i], $typeArray);

用这个:

$index = array_search(trim($csv[$i]), $typeArray);

答案 1 :(得分:1)

当您执行$csv的var_dump时,您会注意到LowkeyWine之前有空格:

array(3) { 
    [0]=> string(6) "Sports" 
    [1]=> string(7) " Lowkey" 
    [2]=> string(5) " Wine" 
}

所以你的array_search会失败。

根据manualdelimiter中的str_get_csv只能是一个字符。您可以改用explodetrim

$csv = explode(', ', $string);

// or 

$index = array_search(trim($csv[$i]), $typeArray);