本文要实现的是typecho文章随机排序,且翻页后文章不会重复输出
种子数
首先当用户访问网站时生成一个随机的数字当做种子(seed),然后传递给后端
后端
后端接受前端传递的seed
,然后将seed
与文章cid
想加得到一个新的数据key,最后按照key
的md5
值进行排序,因为前端那个数字是随机生成的,所以每个人的排序结果都是不一样的,这样就达到了随机的目的,下面是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
即可