Page 1 of 1
Recently Viewed Items
Posted: Tue May 11, 2004 12:05 pm
by zenabi
I have posted this question before but it got lost during the database crash.
How can I implement a Recently Viewed Items list similar to the ones on Amazon and eBay?
A very kind person posted a solution before (using sessions and arrays) but I can't remember their name. If this is you then please post your code again and accept my apology for forgetting who you are.

Posted: Tue May 11, 2004 5:39 pm
by Weirdan
it's not me who helped you

But anyway, here is simple solution (for recently visited urls):
Code: Select all
// file: index.php
session_start();
if(isset($_SESSION['recent'])) {
echo "Recently visited links:<br />";
foreach($_SESSION['recent'] as $url) {
echo "<a href='$url'>$url</a><br />";
}
}
//........
// file: reg_visit.php
if(!isset($_SESSION['recent'])) {
$_SESSION['recent'] = array();
}
$qstr = isset($_SERVER['QUERY_STRING']) ? "?{$_SERVER['QUERY_STRING']}" : "";
array_unshift($_SESSION['recent'],$_SERVER['REQUEST_URI'] . $qstr);
$_SESSION['recent'] = array_slice($_SESSION['recent'], 0, 10); // keep only last 10 pages
// each page which should be displayed in 'recent list' must include following code:
session_start();
include 'reg_visit.php';
//..........
Posted: Wed May 12, 2004 1:45 pm
by zenabi
Thanks for your example!
It's a little different to the example I was given before, but this should get me started. Thanks again.
Posted: Wed May 12, 2004 3:08 pm
by zenabi
OK I've managed to come up with a system similar to the example given above, but have now stumbled across a problem.
Say I have 5 recently viewed items:
1. Hat
2. Shirt
3. Socks
4. Pants
5. Shoes
Now if I click on item 4 (pants) I want it to jump to the top of the list and "push" all the other items down. Can this be done easily?
Thanks in advance to anyone who can help me accomplish this.
Posted: Wed May 12, 2004 3:22 pm
by qads
yup, just have a field called 'time_viewed' and update it every time a item is viewed.
when showing the list, just do ORDER BY time_viewed DESC

Posted: Wed May 12, 2004 3:33 pm
by zenabi
Thanks qads but I was hoping of finding a way to do it using sessions and arrays and not through a database.
Can anyone else help?
Posted: Wed May 12, 2004 3:48 pm
by patrikG
[php_man]array_unshift[/php_man] will do the job.
Posted: Wed May 12, 2004 4:19 pm
by zenabi
Thanks patrickG I've got it now! With a combination of array_shift() and unset() I've got this:
Code: Select all
<?php
$recent = array("Hat", "Shirt", "Socks", "Pants", "Shoes");
print_r($recent);
$item = $recent[3]; //Pants
for ($i=0; $i < count($recent); $i++)
{
if ($recent[$i] == $item)
{
unset($recent[$i]);
}
}
array_unshift($recent, $item);
print_r($recent);
?>
Which outputs exactly what I want:
Code: Select all
Array
(
ї0] => Hat
ї1] => Shirt
ї2] => Socks
ї3] => Pants
ї4] => Shoes
)
Array
(
ї0] => Pants
ї1] => Hat
ї2] => Shirt
ї3] => Socks
ї4] => Shoes
)
Cheers!

Posted: Wed May 12, 2004 4:50 pm
by patrikG