一,将代码放到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]