I've got a website on which I want to display items. These items are stored in a database in the following format:
ID Item Active
1 My item 0
2 My item 1
7 My item 1
8 My item 1
10 My item 0
Note here that the IDs are not necessarily evenly spaced. Each item is either active(1) or inactive(0). I want 3 items to be active at a time and every time my script is called I want the next item to become active and the oldest item to become inactive like so:
ID Item Active
1 My item 0
2 My item 0
7 My item 1
8 My item 1
10 My item 1
and so:
ID Item Active
1 My item 1
2 My item 0
7 My item 0
8 My item 1
10 My item 1
I'm currently struggling with the algorithm to consider the third case above. I can't just pick the highest ID that's active and move to the next item and set that active and at the same time pick the lowest one that's active and make it inactive.
Here's my code so far:
{
for ($i=0;$i<sizeof($videos);$i++)
{
echo $i."]";
if ($videos[$i]->active == 1)
{
if (!isset($first_active))
{
echo "mooh";
echo "[";
echo $first_active = $i;
echo "]";
}
if ( ($i < (sizeof($videos)-1)) && ($videos[$i+1]->active == 0) )
{
$videos[$i+1]->active = 1;
$videos[$i+1]->update();
echo "@".$first_active."|".$videos[$first_active]->id()."@";
$videos[$first_active]->active = 0;
$videos[$first_active]->update();
$first_active = null;
echo "|".$videos[$i+1]->id();
break;
}
elseif ($i == (sizeof($videos)-1))
{
$videos[0]->active = 1;
$videos[0]->update();
$videos[$first_active]->active = 0;
$videos[$first_active]->update();
$first_active = null;
echo "|".$videos[0]->id();
break;
}
}
}
}
This works until I get to the end, e.g. ID 10. It then correctly makes ID 1 active. In the next call, it makes ID 7 active and ID 1 inactive.
Any idea how I can 1) fix my code, 2) tackle this problem smarter?