[英]php array_merge not working for cookies id
我对php merge_array有问题,我正在编写一个cookie,该cookie从html表单的按钮中获取元素ID,然后我创建了一个cookie setcookie(“ info”,$ _REQUEST [“ ELEMENT_ID”] + 1,time()+ 3600)。 我想编写一个数组,将$ array1与表单中的元素ID和$ array2合并,以获取cookie元素。 问题是,当我单击页面上的“购买”按钮时,我在数组上总是有2个元素,新元素和cookie数组中的一个。 Array([0] => [1] => Array([info] => 16我希望获得具有不仅仅是2个元素的array $ 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中,并且希望将其保存在一个数组中,因此您可以将数据作为id的序列化数组存储在cookie中。 现在要做的就是获取当前的ELEMENT_ID,将其添加一个,然后将该值存储到cookie中,该cookie将覆盖已经存在的ID。 因此,我将用以下代码替换所有代码:
<?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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.