如何爆炸cookie并将结果放入多维数组

我是编码新手,所以请善待:)


在一个人们可以上传待售或出租房地产的在线市场上工作,我想用 cookie 建立一个最喜欢的列表。我已经设法使用


setcookie("$flat_rent_id", $flat_rent_id . "__" . "$offering_type", time() + (86400 * 30), '/');

并使用


// 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 

有谁知道为什么?我会非常感谢所有的帮助!


不负相思意
浏览 134回答 1
1回答

慕姐4208626

因为你先说:$explodedCookiesArray[$h][$i] = $item . " " ;然后你说:if ($explodedCookiesArray[1][1] == "house_rent")比较中没有空格字符。这段代码比它需要的要冗长得多。如果我正确理解您的数据,foreach那么您只需要循环中的一行:// test data$_COOKIE = [&nbsp; &nbsp; "PHPSESSID"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> "378b94ed20765e354ec9790832800ed6",&nbsp; &nbsp; "Offering5ce890ed7f11d" => "Offering5ce890ed7f11d__house_rent",&nbsp; &nbsp; "Offering5ce8935b812f6" => "Offering5ce8935b812f6__house_sale",&nbsp; &nbsp; "Offering5ce8f86bbda11" => "Offering5ce8f86bbda11__flat_sale",];$explodedCookiesArray = [];foreach ($_COOKIE as $c) {&nbsp; &nbsp; $explodedCookiesArray[] = explode("__", $c);}if ($explodedCookiesArray[1][1] == "house_rent") {&nbsp; &nbsp; echo "Hello";} else {&nbsp; &nbsp; echo "Goodbye";}输出:Hello真的,您应该做的是将其存储为值的序列化数组而不是多个 cookie。或者将列表存储在数据库中,并在 cookie 中仅保留一个唯一标识符。
打开App,查看更多内容
随时随地看视频慕课网APP