我是编码的新手,所以请客气:)
在一个在线市场上工作,人们可以在上面上传要出售或出租的房地产,我想建立一个包含cookie的收藏列表。我已经设法使用
在cookie中存储了offing_id和offering_typesetcookie("$flat_rent_id", $flat_rent_id . "__" . "$offering_type", time() + (86400 * 30), '/');
并使用
构造一个数组explodedCookiesArray// Construct array of exploded cookies
$h = -1;
$i = -1;
foreach($_COOKIE as $COOKIE => $value) {
$h++;
$i = -1;
$explode = (explode("__", $value, 2));
foreach ( $explode as $item ) {
$i++;
$explodedCookiesArray[$h][$i] = $item . " " ;
}
}
当我使用打印阵列时
// Print the constructed array "explodedCookiesArray
echo "explodedCookiesArray";
for ($i=0; $i <= count($_COOKIE); $i++){
echo "<br>";
for ($j=0; $j <= count($_COOKIE); $j++){
echo $explodedCookiesArray[$i][$j];
}
}
echo "<br>";
我得到了输出
explodedCookiesArray
378b94ed20765e354ec9790832800ed6
Offering5ce890ed7f11d house_rent
Offering5ce8935b812f6 house_sale
Offering5ce8f86bbda11 flat_sale
Offering5ce93dfdcae32 house_rent
Offering5ce9411388315 flat_rent
如果我使用
print_r($explodedCookiesArray);
我得到输出:
Array (
[0] => Array ( [0] => 378b94ed20765e354ec9790832800ed6 )
[1] => Array ( [0] => Offering5ce890ed7f11d [1] => house_rent )
[2] => Array ( [0] => Offering5ce8935b812f6 [1] => house_sale )
[3] => Array ( [0] => Offering5ce8f86bbda11 [1] => flat_sale )
[4] => Array ( [0] => Offering5ce93dfdcae32 [1] => house_rent )
[5] => Array ( [0] => Offering5ce9411388315 [1] => flat_rent ) )
尽管如此,命令
if (isset($explodedCookiesArray[1][1])) {
echo $explodedCookiesArray[1][1] . "<br>";
if ($explodedCookiesArray[1][1] == "house_rent") {
echo "Hello";
} else {
echo "Goodbye";
}
}
输出以下内容:
house_rent
Goodbye
有人知道为什么吗? 我将非常感谢您提供的所有帮助!
答案 0 :(得分:2)
因为您先说:
$explodedCookiesArray[$h][$i] = $item . " " ;
然后您说:
if ($explodedCookiesArray[1][1] == "house_rent")
比较中没有空格。
此代码比所需的要冗长得多。如果我正确理解了您的数据,则只需要foreach
循环中的一行:
// test data
$_COOKIE = [
"PHPSESSID" => "378b94ed20765e354ec9790832800ed6",
"Offering5ce890ed7f11d" => "Offering5ce890ed7f11d__house_rent",
"Offering5ce8935b812f6" => "Offering5ce8935b812f6__house_sale",
"Offering5ce8f86bbda11" => "Offering5ce8f86bbda11__flat_sale",
];
$explodedCookiesArray = [];
foreach ($_COOKIE as $c) {
$explodedCookiesArray[] = explode("__", $c);
}
if ($explodedCookiesArray[1][1] == "house_rent") {
echo "Hello";
} else {
echo "Goodbye";
}
输出:
Hello
确实,您应该做的是将其存储为serialized值数组而不是多个Cookie。或将列表存储在数据库中,并在cookie中仅保留唯一标识符。