排行榜的实现
500名之后,排名就没意义了。
// 获取排行榜
public function getMyRankingList() {
$uid = input('post.uid/d');
if (!$uid) {
$this->json->setErr('10001',lang('10001'));
$this->json->Send();
}
$user = new UserModel();
$user_info = $user->where('id',$uid)->field('id as uid,avatarurl,nickname,continue_anwser_times,usable_integral')->find();
if (!$user_info) {
$this->json->setErr('20001',lang('20001'));
$this->json->Send();
}
$out_data = [];
// 获取前500个排名靠前的用户,如果不在其中,那么你的排名就是 '-' 横杠
$user_info['rank'] = '-';
$top_500 = $user->where('status',UserModel::USER_STATUS_PASS)->order('usable_integral desc,id asc')->limit(500)->column('id');
$offset = array_search($uid,$top_500);
if ($offset !== FALSE) { // 注意了 ,小心排第一被过滤掉
$user_info['rank'] = $offset+1;
}
$out_data = $user_info;
$this->json->setAttr('data',$out_data);
$this->json->Send();
}
/**
* 分页
*/
public function getRankingList() {
$page = input('post.page/d',1);
$per_page = input('post.per_page/d',config('normal_per_page'));
// 获取商品数据
$user = new UserModel();
$where['status'] = UserModel::USER_STATUS_PASS;
// 获取分页数据
$count = $user->where($where)->count();
$total_page = ceil($count / $per_page);
if ($page > $total_page) {
$this->json->setErr(0,lang('tips_no_more'));
$return_data = ['data_list' => [],'total_page' => $total_page, 'current_page'=>$page];
$this->json->setAttr('data',$return_data);
$this->json->Send();
}
$user_list = $user->where($where)
->order('usable_integral desc,id asc')
->limit((($page - 1) * $per_page) . "," .$per_page)
->field('id as uid,avatarurl,nickname,continue_anwser_times,usable_integral')
->select();
foreach ($user_list as $k=>&$v) {
$v['rank'] = (($page - 1) * $per_page) + ($k + 1);
}
$return_data = ['data_list' => $user_list,'total_page' => $total_page, 'current_page'=>$page];
$this->json->setErr(0, '获取成功');
$this->json->setAttr('data',$return_data);
$this->json->Send();
}