doufan6033 2014-05-08 09:49
浏览 44
已采纳

限制cookie中的数组大小

I have the following function to set a cookie on each indiviual product page a user visits on my website.

function setcookie() {

    $entry_id = '787';

    if (isset($_COOKIE['recently_viewed'])) {

        $currentSession = unserialize($_COOKIE['recently_viewed']);

        if (!in_array($entry_id, $currentSession)) {

            if (count($currentSession) > 5) {
                unset($currentSession[0]);
            }

            $currentSession[] = $entry_id;

        } else {}

        $currentSession = serialize($currentSession);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    } else {

        $recently_viewed[] = $entry_id;
        $currentSession = serialize($recently_viewed);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    }

}

In this function I am trying to limit the number of items stored in the cookies array.

When the cookies array has 6 items in it, I want to remove the first (oldest) item in that array and then add the new item (so there is never more than 6 items, but always adds the new one).

I have used the following, but it doesn't always seem to work. Sometimes it removes the first item when there are more than 5, but other times it just keeps adding them so there are more than 6.

if (count($currentSession) > 5) {
    unset($currentSession[0]);
}

Can anyone tell me if there is a better way to achieve this?

  • 写回答

2条回答 默认 最新

  • duaeim2874 2014-05-08 10:02
    关注

    You definitely should use session.

    session_start();
    $entry_id = '788';
    if (!is_array($_SESSION['recently_viewed'])) {
        $_SESSION['recently_viewed'] = array();
    }
    //  add the item to the begining
    array_unshift($_SESSION['recently_viewed'], $entry_id);
    // ensure unique entries
    $_SESSION['recently_viewed'] = array_unique($_SESSION['recently_viewed']);
    // keep first 5 entries
    $_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 5);
    echo 'recent: ' . print_r($_SESSION['recently_viewed'], true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?