如何获取数组中的随机元素以及如何从mysql中获取随机行?

I have been asked to get related stuff to what the user has in his items

so as far as the database was created this items table stores the category name so, i thought to get the category name and save it into an array

and then do a for loop and get one random value from it

and after that get a random row from mysql database so anyone has an idea how to do this

in other words i want to know how to get a random value from an array and a random row from mysql

Thanks in advance.

use

 $rand_keys = array_rand($input, 1);

see example http://php.net/manual/en/function.array-rand.php for php and for mysql

 SELECT * FROM tbl_name ORDER BY RAND() LIMIT 1

use this

To get a random element from an array in PHP you can use array_rand.

To get a random row from a MySQL query you can use RAND() so something like

ORDER BY RAND() LIMIT 1

But note that this method in MySQL can have performance implications.

quote from http://php.net/manual/de/function.rand.php:

ilya dot iz at i dot ua 27-Jul-2011 08:09 I had to come up with a quick way to get a random row from a table, and came up with the following: ...

Should be easy to get a random value from an array with something like rand(0,count(arrayvar))