tk挠痒痒网址发布页-秘密武器
历史搜索

帝国CMS全站高效随机调用:毫秒级性能优化与实现方法

游客2025-05-16 13:22:01

调用效率极高,90万数据随机调用测试,只需要500毫秒

调用可指定栏目调用,也可整个表调用

安装简单,只需一个函数

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;
}

将代码放到e/class/userfun.php文件中

<?php
$id = ecms_rand(1,50);
?>
调用的文章id:
[e:loop={0,50,3,0,"id in ($id)"}]   
<?=$bqr['id']?>             
[/e:loop]


本文是由用户"游客"发布,所有内容的版权归原作者所有。

推荐阅读