<?php
require 'system/include/common.inc.php ';
$n = 10; //随机显示的记录数
$results = $result = array(); //记录结果的数组
$rowNum = mysql_result(mysql_query( "SELECT COUNT(*) AS cnt FROM test "), 0, 0);
echo $rowNum;
if($rowNum < 50) { //数据量小的话,这样反而可以提高效率,当然50可以随便改
$query = mysql_query( "SELECT * FROM test ORDER BY rand() LIMIT 0,$n ");
while($result = mysql_fetch_array($query)) {
$results[$result[ 'id ']] = $result;
}
} else {
//随机的范围
$maxNum = mysql_result(mysql_query( "SELECT MAX(id) AS maxid FROM test "), 0, 0);
$minNum = 1;
//存放记录的数组
$results = array();
//存放生成的id,用来判断是否已经出现过!
$existIds = array();
//随机的id集合 格式为 xx,xx,xx,xx,用来查询记录
$limitNum = $randId = $randIds = ' ';
//根据已经产生的记录来动态控制下次查询的记录数
$limitNum = $n;
do {
$query = $result = ' ';
$randIds = ' '; //清除上次查询id
$comma = ' ';
$j = 0;
while($j < $n) { //while($j < 2 * $n) { 随机产生n个数字,可以增加一定值,来加大命中率
mt_srand((float)microtime() * 1000000);
$randId = mt_rand($minNum, $maxNum);
if(!in_array($randId, $existIds)) {
$existIds[] = $randId; //将产生的id全部记录到$existIds数组中,用来产生不重复的记录id
$randIds .= $comma . $randId;
$comma = ', ';
$j++;
}
}
$query = $db-> query( "SELECT * FROM test WHERE id IN ($randIds) LIMIT 0,$limitNum ");
while($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机
$results[$result[ 'id ']] = $result; //记录结果内容
}
$limitNum = $n - count($results);
}while(count($results) < $n);
}
var_dump($results);
?>
读取数据库随机的信息
最新推荐文章于 2025-12-26 18:13:00 发布
2336

被折叠的 条评论
为什么被折叠?



