dpbdl44228 2013-06-11 19:26
浏览 75
已采纳

从数据库中选择后,从数组中选择一个随机值

I'm trying to get a random value from an array that is populated with data from the database. I'm selecting some products from the DB and display them on the front page, but i need to display different (random) producs everytime the page is reloaded.

$row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
$row2 = mysql_fetch_assoc($row);

So, i think that $row2 is now an array, and has all the infos that i selected previously from the database. How do i select a random 'row' from that array now?

Thanks

  • 写回答

3条回答 默认 最新

  • dongpan8439 2013-06-11 19:30
    关注

    If you want to select a random entry, you could do something like this:

    $myRows=array();
    $row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
    while($row2 = mysql_fetch_assoc($row))
        $myRows[]=$row2;
    
    $randomEntry=$myRows[array_rand($myRows)];
    

    If you wanted a random field of that entry though, you should use array_rand like Bernhard Poiss pointed out.

    $row = mysql_query("SELECT * FROM anunt WHERE lichidareStoc = 0 ORDER BY anuntID DESC") or die(mysql_error());
    $row2 = mysql_fetch_assoc($row);
    $randomField=$row2[array_rand($row2)];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL