我试图按查看顺序显示最近查看的记录(最近查看的记录在列表顶部)。
最多显示4个产品。该代码未按此顺序显示记录。谁能看到什么错?
我认为在数据库中找到记录后,数组的显示顺序不正确:
<?php
//
// --------------------------------------------------------------
//
// set cookie for recent items
//
// ---------------------------------------------------------------
//
$currentProduct = $id;//gets product id from URL that was viewed
//Set default of viewed products to empty array
$viewed_products = array();
//If there is a viewed cookie value - use it
if(isset($_COOKIE['recently_viewed9']))
{
//$viewed_products = unserialize($_COOKIE['recently_viewed']);
$viewed_products = (array) explode( ',', $_COOKIE['recently_viewed9']);
}
//If the currently viewed product exists in the array remove it
if(in_array($currentProduct, $viewed_products))
{
unset($viewed_products[array_search($currentProduct, $viewed_products)]);
}
//Add the current product to the end of the array
$viewed_products[] = $currentProduct;
//Ensure length of array is no more than 3 items
if (sizeof( $viewed_products ) > 4 )
{
array_shift( $viewed_products );
}
// Store cookie
setcookie( 'recently_viewed9',implode( ',', $viewed_products ), time()+(86400 * 30), '/' );//changed here
//
// ------------------------------------------------------------------
//
// show recent items SQL
//
// ------------------------------------------------------------------
//
//$currentProduct = $id;//gets product id from URL that was passed
$viewed_products="";
if(isset($_COOKIE['recently_viewed9']))
{
//$viewed_products = unserialize($_COOKIE['recently_viewed']);
$viewed_products = (array) explode( ',', $_COOKIE['recently_viewed9']);
//Run query to get records for recently viewed products
$listOfviewed = implode( ',',$viewed_products);
$max = sizeof($viewed_products);
$recentProducts = $db->get_results("SELECT id, prodcode, artist, title FROM records WHERE id IN ($listOfviewed) ");
//Create output for list of recent products
$output = "";
echo' <div style="text-align: center">';
foreach($recentProducts as $prod )
{
// show products
// etc ......
}
?>