修罗高性能获取随机帖子探讨
xiunoa 2020-8-19



自己写的高性能获取随机帖子代码,分享给大家,不足之处请高手指点!为什么不直接用MySQL语句,据我测试发现兼容性不好,不知道是否我MySQL配置问题。如果您有更好的方法请多指!

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function get_rand_thread($num = 20, $cond array()){
    global $db,$forumlist_show;
    $tablepre $db->tablepre;
    $fids = arrlist_values($forumlist_show'fid');
    $cond['fid'] = $fids;
    $condsql = db_cond_to_sqladd($cond);
    $maxmincount = db_sql_find_one("SELECT MAX(tid), MIN(tid), COUNT(*) FROM {$tablepre}thread {$condsql}");
    list($max$min$count) = array_values($maxmincount);
    if($count <= $num){
        //符合条件的数据比指定的数据还少,直接全部读取吧,打散一下
        $sql "SELECT * FROM {$tablepre}thread {$condsql}";
        $threads = db_sql_find($sql);
        shuffle($threads);
    else {
        //随机读取帖子,万一存在不符合条件的帖子,数量就少于$num个了,那继续读取,直到数量足够为止
        $threads array();
        do {
            $rndtids array();
            //生成随机tid,防止重复
            for($i=$num;$i>0;$i--){
                do {
                    $rand = rand($min$max);
                while(in_array($rand$rndtids));
                $rndtids[] = $rand;
            }
            $cond['tid'] = $rndtids;
            $condsql = db_cond_to_sqladd($cond);
            $sql "SELECT * FROM {$tablepre}thread {$condsql}";
            $rndthreads = db_sql_find($sql);
            $threads += $rndthreads;
        while(count($threads)<$num);
    }
    //数据格式化一下
    if($threadsforeach ($threads as &$thread) thread_format($thread);
    return $threads;
}


最新回复 (4)
全部楼主
  • 345290
    2020-10-18 2
    0
    给力,谢谢大佬
  • li3295
    2022-3-29 3
    0
    沙发我没有,板凳我没有,板也没有,只好站在后面排队支持! 
  • gaojituan
    2022-4-14 4
    0
    哈哈,不错哦!
  • gaojituan
    2022-4-14 5
    0
    哈哈,不错哦!
返回
xiunoa
超版
285
主题数
422
帖子数
扫码访问