I have a classifieds website, and when users click on an ad, an array element containing the ad id is set to a cookie.
Then on the main page, the 'last visited ads' is shown.
Problem is, I have a limit on the nr of 'last visited ads' ( set to 10 ).
So, if the cookie array contains more than 10 elements, I want the elements to be replaced one by one.
I have managed to replace only the last element in the array once the cookies-array-length > 10
. But it only keeps overwriting the last element, when I want it to replace next one (last - 1).
Example: Cookie has more than 10 array elements. I click on an ad. Then the ad-id which gets replaced is the last element, ALWAYS. BUT, I want it to replace elements one by one starting from the last. (nr 10, nr 9, nr 8) so that it doesn't overwrite nr 10 all the time.
Here is the code:
if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000; //20 days
$ad_arr = unserialize($_COOKIE['watched_ads']);
$arr_elem = count($ad_arr);
for ($i=0; $i<$arr_elem; $开发者_开发百科i++){
if ($ad_arr[$i] == $ad_id) { $ad_in_cookie_exists = 1;
}
}
if ($arr_elem>10 && $ad_in_cookie_exists!=1){
$ad_arr[$arr_elem-1]=$ad_id; // HERE IS THE PROBLEM, IT REPLACES LAST ONE, CANT FIGURE OUT HOW TO REPLACE ONE BY ONE!
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
else if ($ad_in_cookie_exists !=1 && $arr_elem<=10){
$ad_arr[] = $ad_id; echo "andra";
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
}
So, do you have any ideas on how to solve this?
Thanks
PS: if you need more input, tell me and I will update the Q!
Why not replace the oldest ad click? So rather than treating it as a [last in first out](http://en.wikipedia.org/wiki/LIFO_(computing)) structure it gets treated as a [first in first out](http://en.wikipedia.org/wiki/FIFO_(computing)) structure.
Take a look at array_shift()
if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000;
$ad_arr = unserialize($_COOKIE['watched_ads']);
$arr_elem = count($ad_arr);
if ( in_array($ad_id) == FALSE ){
if ( $arr_elem > 10 ){
$ad_arr = array_shift($ad_arr);
}
$ad_arr[] = $ad_id;
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
}
精彩评论