efficient function
function user_randId($table='news'){
global $dbtbpre,$empire;
$filePath = ECMS_PATH . 'e/maxID'.md5($table).'.txt'; // 文件路径
if(file_exists($filePath)) {
$fileCreateTime = filectime($filePath); // 获取文件创建时间(Unix 时间戳)
$oneDayAgo = strtotime('-1 day'); // 当前时间减去一天的时间戳
if ($fileCreateTime < $oneDayAgo) {
unlink($filePath);
$start = $empire->fetch1("select id from {$dbtbpre}ecms_{$table} where newstime <= ".time()." order by id ASC limit 1");
$end = $empire->fetch1("select id from {$dbtbpre}ecms_{$table} where newstime <= ".time()." order by id DESC limit 1");
$index['min'] = $start['id'];
$index['max'] = $end['id'];
file_put_contents($filePath,json_encode($index));
} else {
$index = json_decode(file_get_contents($filePath),true);
}
} else {
$start = $empire->fetch1("select id from {$dbtbpre}ecms_{$table} where newstime <= ".time()." order by id ASC limit 1");
$end = $empire->fetch1("select id from {$dbtbpre}ecms_{$table} where newstime <= ".time()." order by id DESC limit 1");
$index['min'] = $start['id'];
$index['max'] = $end['id'];
file_put_contents($filePath,json_encode($index));
}
$randnum=300; //随机数量
$randids='';
$randdh='';
for($i=1;$i<=$randnum;$i++)
{
$randids.=$randdh.rand($index['min'],$index['max']); //1为最小ID,100000为最大ID
$randdh=',';
}
return $randids;
}Supports querying different data tables. The default is the news table. The calling method is:
<? $randids = user_randId('news1');?>
[ecmsinfo]3,8,32,0,0,15,0,"id in ($randids)"[/ecmsinfo]Efficient Code Second Edition:
The second version can be said to be more intelligent and adopts caching technology.
Highly efficient call version 1:
<?php
$randnum=32; //随机数量
$randids='';
$randdh='';
for($i=1;$i<=$randnum;$i++)
{
$randids.=$randdh.rand(1,100); //1为最小ID,100000为最大ID
$randdh=',';
}
?> [e:loop={1,32,0,0,"id in ($randids)"}]
<li>
<a href="<?=$bqsr['titleurl']?>" title="<?=$bqr['title']?>"><?=$bqr['title']?></a>
</li>
[/e:loop]