AI智能摘要
本文提供了一段帝国cms的高效随机调用函数代码`ecms_rand`。该函数需放置在`e/class/userfun.php`文件中,其核心是生成一个`d/news.json`缓存文件存储文章ID,避免重复查询数据库以实现毫秒级调用。通过指定栏目ID和数量,函数返回随机ID串,再结合`e:loop`标签即可展示内容。
— 此摘要由AI分析文章内容生成,仅供参考。
一,将代码放到e/class/userfun.php文件中
function ecms_rand($classid,$num){
global $empire,$dbtbpre;
$file_cache = ECMS_PATH."d/news.json"; //缓存文件
//缓存整个news表的数据
if(!file_exists($file_cache)){
//查询分类
$hm_class=$empire->query("select classid from {$dbtbpre}enewsclass");
while($hm_r=$empire->fetch($hm_class))
{
//查询分类下面的所有id
$hm_news=$empire->query("SELECT id FROM `{$dbtbpre}ecms_news` WHERE `classid` = {$hm_r[classid]}");
while($hm_nr=$empire->fetch($hm_news))
{
$news_data[$hm_r['classid']][] = $hm_nr[id];
}
}
file_put_contents($file_cache,json_encode($news_data));
}
//获取缓存数据文件
$file_arrs = json_decode(file_get_contents($file_cache),true);
if($classid=="0"){
$num = ceil($num/count($file_arrs));
foreach($file_arrs as $k=>$v)
{
if(count($v) <= $num){ continue;}
//根据数据表获取id,每个栏目随机分配文章id
$key_array = array_rand($file_arrs[$k],$num);
foreach($key_array as $v)
{
$rand_id.= $file_arrs[$k][$v].",";
}
}
$rand_id = rtrim($rand_id,",");
}else{
if(count($file_arrs[$classid]) <= $num){
$key_array = array_rand($file_arrs[$classid],count($file_arrs[$classid]));
}else{
$key_array = array_rand($file_arrs[$classid],$num);
}
//根据数据表获取id,每个栏目随机分配文章id
$key_array = array_rand($file_arrs[$classid],$num);
foreach($key_array as $v)
{
$rand_id.= $file_arrs[$classid][$v].",";
}
$rand_id = rtrim($rand_id,",");
}
return $rand_id;
}
二、模板调用方式:
<?php
$id = ecms_rand(1,50);
?>
调用的文章id:
[e:loop={0,50,3,0,"id in ($id)"}]
<?=$bqr['id']?>
[/e:loop]


腾讯云 12-20 广告

