Looping on an array to always choose the next value

3

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

This is my array, which I get 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 the one that was chosen was the Pedro (I get the id that was previously saved), I need to next save the id luiz in the DB, and so on ...

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

    
asked by anonymous 11.03.2014 / 22:52

2 answers

0

After randomly selecting a user 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 to bring the next user with id greater than the current one, limiting the query to one result, that is, only brings the next one.

If id is already the last one in the list, a way to "restart" the loop would be to use if in PHP to restart $id_atual to the smallest possible.     

11.03.2014 / 23:26
0

Look at the PHP documentation, you may not 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 inner pointer of an array
reset () - Makes the internal pointer of an array point to its first element
each () - Returns the current key / value pair of an array and advances its cursor

link

    
20.05.2016 / 15:01