我有一个JavaScript,它可以保存复选框状态,将其放入cookie中,然后在表单中重新填充我的复选框。此时,我要做的是用php将一堆"if语句"组合在一起,然后将那些"true"的语句转换为字符串。
以下是当我回显$_COOKIE["elementValues"]时得到的结果。1,2,3表示每个表单输入复选框的id号。
{"1":false,"2":false,"3":false,buttonText":""}
以下是我尝试用PHP做的事情。
if ($_COOKIE["1"]=true)
{ $arguments[] = "AND 2kandunder = 'yes'";
}
if ($_COOKIE["2"]=true)
{ $arguments[] = "AND 2kto4k = 'yes'";
}
if ($_COOKIE["3"]=true)
{ $arguments[] = "AND 2kandup = 'yes'";
}
if(!empty($arguments)) {
$str = implode($arguments);
echo "string: ".$str."<br>;
问题是我回显了我的$str,即使$_COOKIE["elementValues"]中的所有复选框都是"false",它仍然会回显and 2kto4k='yes'和2kandunder='yes'and 2kandup='yes'。只有当id为"true"时,我才能编写这些if语句将参数添加到字符串中?
这里是var_dump($_COOKIE);
array(3) { ["PHPSESSID"]=> string(32) "4b4bbcfc32af2f41bdc0612327933887" [2]=> string(6) ""true"" ["elementValues"]=> string(47) "{"1":false,"2":false,"3":false,"buttonText":""}" }
{"1":false,"2":false、"3":false和"buttonText":"}
编辑
根据您的评论,看起来$_COOKIE["elementValues"]
是一个JSON
字符串。你必须按照我的编辑做。
你正在做你想做比较的作业。这是您更正的代码:
首先解码JSON
字符串:
$cookie = json_decode($_COOKIE["elementValues"], true); // note the second argument to true to make it an associative array
然后,按照您的条件,此方式:
if ($cookie["1"] == true) // note the ==
{
$arguments[] = "AND 2kandunder = 'yes'";
}
if ($cookie["2"] == true) // note the ==
{
$arguments[] = "AND 2kto4k = 'yes'";
}
if ($cookie["3"] == true) // note the ==
{
$arguments[] = "AND 2kandup = 'yes'";
}
或此方式(较短):
if ($cookie["1"]) // casts variable as boolean if it's not
$arguments[] = "AND 2kandunder = 'yes'";
if ($cookie["2"]) // casts variable as boolean if it's not
$arguments[] = "AND 2kto4k = 'yes'";
if ($cookie["3"]) // casts variable as boolean if it's not
$arguments[] = "AND 2kandup = 'yes'";