PHP array_merge不适用于 Cookie ID


php array_merge not working for cookies id

我在使用 PHP merge_array 时遇到了问题,我正在编写一个从 HTML 表单中的按钮获取元素 ID 的 cookie,然后我制作了一个 cookie setcookie("info", $_REQUEST["ELEMENT_ID"]+1, time()+3600)。 我想编写一个数组,该数组将 $array 1 与表单中的 ellement id 合并,并将 $array 2 合并以获取 cookie 元素。当我单击页面上的购买按钮时出现问题,数组上总是有 2 个元素,新元素和一个来自 cookie 数组的元素。数组 ( [0] => [1] => 数组 ( [信息] => 16 我希望获得不仅仅是 2 个元素的数组$result,以便我可以使用 id 将名称、照片和其他属性获取到购物车中

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
<?
$array1=array($_REQUEST["ELEMENT_ID"]);
if(!isset($_COOKIE["info"])){
    setcookie("info", $_REQUEST["ELEMENT_ID"]+1, time()+3600);
    $w = $_REQUEST["ELEMENT_ID"]+1;
    print_r($_COOKIE);
}
echo"<br/>";
$array2=array($_COOKIE);
$result= array_merge($array1, $array2);
print_r($result);

?>

编辑:

好的,现在我更好地理解了你想做什么,这就是我的建议。由于您希望在 Cookie 中存储历史数据,并且希望在数组中维护它,因此您可以将数据存储为 cookie 中的序列化 id 数组。您现在要做的是获取当前ELEMENT_ID,向其添加一个,然后将该值存储到cookie中,这将覆盖已经存在的内容。所以我会用这个替换你所有的代码:

<?php
    // do your checks
    if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();
    // 1: if cookie exists, grab the data out of it
    $historical_element_ids = array(); // initialize the variable as an array
    if(isset($_COOKIE['info'])){
        // retrieve the previous element ids as an array
        $historical_element_ids = unserialize($_COOKIE['info']);
    }
    // 2: add the new id to the list of ids (only if the id doesn't already exist)
    // the cookie will remain unchanged if the item already exists in the array of ids
    if(!in_array($_REQUEST['ELEMENT_ID'], $historical_element_ids)){
        $historical_element_ids[] = $_REQUEST['ELEMENT_ID']; // adds this to the end of the array
        // 3: set the cookie with the new serialized array of ids
        setcookie("info", serialize($historical_element_ids), time()+3600);
    }
    // display the cookie (should see a serialized array of ids)
    print_r($_COOKIE);
    echo"<br/>";
    // accessing the cookie's values
    $result = unserialize($_COOKIE['info']);
    print_r($result);
?>