PDA

Click to See Complete Forum and Search --> : FIFO table


slice
May 1st, 2006, 08:26 AM
I want to have table with just 3 records (rows) and i want work it as FIFO

if i add 100
it will go on 1st row
and then if i add 200
it will go in 1st row and 100 should go in 2nd row
and then if i add 300
it will go in 1st row and 200 will go in 2nd row and 100 will go in 3rd row

and when i would add 400 then it would go in 1st row with 300 in 2nd row and 200 in 3rd row but 100 should be deleted.

little complex :)

But i am finding here an easy way to do it.
Thank You.

visualAd
May 1st, 2006, 08:32 AM
array_shift() (http://uk2.php.net/manual/en/function.array-shift.php)

slice
May 1st, 2006, 11:54 PM
thanks for the post visualad
but this function doesn't relate to the problem because i want to keep 3 rows (records) in the table and when new record is added last record should be dropped automatically.

visualAd
May 2nd, 2006, 02:06 AM
Sorry, the function I meant to post was array_unshift. This prepends an element to the front of an array. The type of FIFO you are asking for is a pipe as a normal FIFO structure grows in size similar to how a queue inside a shop grows.

If you were to describe this pipe using an object, you could have something like this:

class Pipe
{
private $pipeArray;
private $size;
private $pointer = 0;

public function __construct($size)
{
$this->size = (int) $size;
$this->pipeArray = Array($this->size);
}

/**
* Adds data to the pipe. If the pipe has reached its maximum
* size the first element in the pipe is returned and removed from the
* pipe to make room for the new element.
*/
public function push($data)
{
$first = null;

if ($this->pointer == $this->size - 1) { // pipe is full
$first = array_pop($this->pipeArray);
} else {
++$this->pointer;
}

array_unshift($this->pipeArray, $data); // add the data

return $first;
}

/**
* Pulls the first element from the pipe, reducing its contents by 1.
*/
public function pop()
{
$data = null;

if ($this->pointer != 0) {
--$this->pointer;
$data = array_pop($this->pipeArray);
}

return $data;
}

/**
* Returns the current pipe as an array.
*/
public function get_pipe_as_array()
{
return array_reverse($this->pipeArray);
}
}


The object can then be used as follows:

$pipe = new Pipe(3); // makes a pipe containing 3 elements
$pipe->push(100);
$pipe->push(200);
$pipe->push(300); // pipe should now be full
$pipe->push(400);

print_r($pipe->get_pipe_as_array());



Note, that the array is returned in reverse order, so you can traverse it using a foreach loop and it will maintain the FIFO nature of the pipe.