文章随机排序方法
注册

文章随机排序方法

本文要实现的是typecho文章随机排序,且翻页后文章不会重复输出

种子数

首先当用户访问网站时生成一个随机的数字当做种子(seed),然后传递给后端

后端

后端接受前端传递的seed,然后将seed与文章cid想加得到一个新的数据key,最后按照keymd5值进行排序,因为前端那个数字是随机生成的,所以每个人的排序结果都是不一样的,这样就达到了随机的目的,下面是mysql语句实例

$seed=接受前端传递的随机数字;
$select = $this->db->select(
            'table.contents.cid',
            'table.contents.title',
            'table.contents.slug',
            'table.contents.created',
            'table.contents.authorId',
            'table.contents.modified',
            'table.contents.type',
            'table.contents.status',
            'table.contents.text',
            'table.contents.commentsNum',
            'table.contents.order',
            'table.contents.template',
            'table.contents.password',
            'table.contents.allowComment',
            'table.contents.allowPing',
            'table.contents.allowFeed',
            'table.contents.parent',
            '('.$seed.'+table.contents.cid) as key')->from('table.contents')->where('table.contents.type = ?', 'post');
$select->where('table.contents.status = ?', 'publish')
            ->where('table.contents.created < ?', $this->options->time);
$select->order('MD5(key)', \Typecho\Db::SORT_DESC);

最后

因为在实际使用中还要考虑翻页后的情况,所以后端或者前端要把第一次生成的seed参数存起来用于翻页后使用,使用cookie或则直接给翻页按钮追加get参数都可以,只要保证用户翻页后能获取到之前生成的seed即可

泽泽社长 Last updated 2024-12-16 Created 2024-12-16 121

大纲
加载中