使用php根据过去的用户首选项检查复选框


Using php to check checkboxes based on past user preferences?

我试图根据存储在CSV中的先前用户首选项检查复选框,但它只运行检查CSV中的第一个索引并跳过其余部分。在下面的代码中,如果我向它传递一个CSV文件"Sports, Lowkey, Wine",我希望它在页面加载时检查这三个,但它只检查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> ";

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

与这个:

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

当您对$csv进行var_dump时,您会注意到LowkeyWine之前有一个空格:

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

所以你的array_search会失败。

根据手册,str_get_csv中的delimiter只能是一个字符。您可以使用explodetrim代替。

$csv = explode(', ', $string);
// or 
$index = array_search(trim($csv[$i]), $typeArray);