Looping an array to always choose the next value

Asked

Viewed 263 times

4

I have an array of users and need to make a looping between them. It will work like this, every time someone makes a request on the page, I need to be recorded in the database the next user of what was previously chosen.

This is my array, which I take from registered users, this array can change.

array(
    (int) 1 => 'Joao',
    (int) 6 => 'Pedro',
    (int) 7 => 'Luiz',
    (int) 9 => 'Vinicius'
)

That is, if in the previous request who was chosen was the Pedro (picked up the id that was saved earlier) , need that next time he save the id of the Luiz in the BD, and so on...

My doubt is on, how to "walk" with the values of this array based on the last recorded value?

2 answers

0


After selecting a user randomly from your database, you could use this query to select the "next" id after the current one:

SELECT * FROM sua_tabela WHERE id_usuario > $id_atual ORDER BY id_usuario ASC LIMIT 1

What the query does, basically, is bring the next user with id greater than the current, limiting the query to a result, that is, only brings the next.

In case the id to be the last one on the list, a way to "restart" the loop would be to use a if in PHP to restart $id_atual as little as possible.

0

Look at the PHP documentation, maybe you don’t even have to go to the bank

See these functions:

Current() - Returns the current element in an array
end() - Makes the internal pointer of an array point to its last element
next() - Advance the internal pointer of an array
reset() - Makes the internal pointer of an array point to its first element
each() - Returns the key pair/current value of an array and advances its cursor

http://php.net/manual/en/function.next.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.