最近查看的Cookie数组 - 需要从数组和限额Cookie中提取数据到5个ID [英] Cookie array for Recently Viewed - need to extract data from array and cap cookie to 5 IDs

查看:178
本文介绍了最近查看的Cookie数组 - 需要从数组和限额Cookie中提取数据到5个ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为网站创建最近查看的功能。这个想法是,您在右侧导航栏中有一个框,显示您最近查看的3个产品。

I am trying to create a recently viewed feature to a website. The idea is that you have a box in the right nav that shows your last 3 products viewed. You don't need to be logged it and it's no problem if the user clears cookies, it just starts over.

根据我研究的内容,最好的方法是,这是通过一个cookie数组(相对于设置5个cookie或保持添加cookie或在mysql中做某事)。

From what I've researched, the best way to do this is through a cookie array (as opposed to setting 5 cookies or keep adding cookies or doing something in mysql).

我有2个问题:


  1. 首先,数组保持添加值,我想让它覆盖它的3个值,从那里删除最旧的,然后添加最新的值。因此,如果您按照此顺序访问了7个产品页ID:100,200,300,400,500,600,150,则Cookie应存储值(500,600,150)。第一个是3中最老的,最后一个是最新的。

  2. 第二,我不清楚如何将数组提取成可用的数组。该数组是ID号,我想我需要查询数据库。

当我把它放在页面上:

COOKIE:  <?php echo $cookie; ?>

我得到:

COOKIE: a:7:i:0;s:3:"100";i:1;s:3:"200";i:2;s:3:"300";i:3;s:3:"400";i:4;s:3:"500";i:5;s:3:"600";i:6;s:3:"150";}

这是我的代码:

//set product id
$product_id = [//some stuff here sets the product id]
// if the cookie exists, read it and unserialize it. If not, create a blank array
if(array_key_exists('recentviews', $_COOKIE)) {
    $cookie = $_COOKIE['recentviews'];
    $cookie = unserialize($cookie);
} else {
    $cookie = array();
}

// add the value to the array and serialize
$cookie[] = $product_id;
$cookie = serialize($cookie);

// save the cookie
setcookie('recentviews', $cookie, time()+3600);

如何先获取cookie保存3个值并删除最旧的值?
什么是最好的方法来提取这些ID到我可以放入一个查询?.... str_replace?

How do I first get the cookie to hold 3 values and drop the oldest? What is the best way to extract those IDs into something I can put into a query?....str_replace?

这提出了另一个问题,是我应该把URL,锚文本和产品的几个属性到cookie,而不是查找它与php / mysql?

This brings up another question, which is should I just put the URL, anchor text, and a couple of attributes of the product into the cookie and not look it up with php/mysql?

一如既往,提前感谢。

推荐答案

这里是我最终决定myssef的答案:

Here was the answer I ended up figuring out myssef:

// if the cookie exists, read it and unserialize it. If not, create a blank array
    if(array_key_exists('recentviews', $_COOKIE)) {
        $cookie = $_COOKIE['recentviews'];
        $cookie = unserialize($cookie);
            } else {$cookie = array();}

    // grab the values from the original array to use as needed
    $recent3 = $cookie[0];
    $recent2 = $cookie[1];
    $recent1 = $cookie[2];

这篇关于最近查看的Cookie数组 - 需要从数组和限额Cookie中提取数据到5个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆