download2014711
2012-04-08 09:22 阅读 371
已采纳

如何获取数组中的随机元素以及如何从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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douchun9719 douchun9719 2012-04-08 09:27

    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

    点赞 4 评论 复制链接分享
  • douzhi9395 douzhi9395 2012-04-08 09:28

    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.

    点赞 6 评论 复制链接分享
  • douyiyi5284 douyiyi5284 2012-04-08 09:35

    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))

    点赞 评论 复制链接分享

相关推荐