模仿瀏覽器歷史機制,利用 Cookie 儲存用戶瀏覽過的商品/文章資訊(ID、標題、價格、縮圖、連結),按時間倒序排列,限制顯示筆數,提供優質的用戶體驗。
// 參數:ID、標題、價格、縮圖、當前頁面 URL
cookie_history($id, $info['title'], $info['price'], $info['pic'], $thisurl);
<?php
// 時間倒序排序回調
function my_sort($a, $b) {
$a = substr($a, 1); // 移除前綴 't'
$b = substr($b, 1);
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1; // 較大時間戳排前面
}
// 寫入/更新歷史
function cookie_history($id, $title, $price, $img, $url) {
$dealinfo = compact('title', 'price', 'img', 'url');
$timeKey = 't' . NOW_TIME; // 唯一鍵名,含時間戳
$newItem = array($timeKey => json_encode($dealinfo));
if (!cookie('history')) {
cookie('history', $newItem); // 初始化
} else {
$history = array_merge(cookie('history'), $newItem);
uksort($history, "my_sort"); // 按時間鍵倒序
$history = array_unique($history); // 去重(同一商品多次瀏覽保留最新)
if (count($history) > 4) { // 限制最多 4 筆
$history = array_slice($history, 0, 4);
}
cookie('history', $history);
}
}
// 讀取歷史並解碼
function cookie_history_read() {
$arr = cookie('history');
$list = array();
foreach ((array)$arr as $k => $v) {
$list[$k] = json_decode($true);
}
return $list;
}
$this->assign('history', cookie_history_read());
<volist name="history" id="vo">
<div class="history-item">
<a href="{$vo.url}">
<img src="{$vo.img}" alt="{$vo.title}" width="50" height="50" />
<span>{$vo.title}</span>
<em>{$vo.price}</em>
</a>
</div>
</volist>
t{NOW_TIME} 確保唯一且可排序。array_slice 截取前 4 筆,避免 Cookie 膨脹。