跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

怎么用PHP+Redis实现排行榜

通过 php 和 redis 实现一个小功能排行榜,用的数据类型是有序集合:zrevrange 递增排序,zrange 递减排序
/** * 排行榜 */public function rank() {// $this->zrem($this->cachekey);$this->redis->del($this->cachekey);$dataOne = [];for ($i=0; $i < 5; $i++) { // 生成随机数$num = rand(0,100);// 生成随机字符串$str = $this->get_random(6,'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ'); $this->redis->zadd($this->cachekey,$num,json_encode(['name'=>$str]));// 由大到小排序$dataOne = $this->redis->ZREVRANGE($this->cachekey, 0, -1, true);// 由小到大排序$dataTow = $this->redis->ZRANGE($this->cachekey, 0, -1, true); }echo "
";print_r($dataOne);print_r($dataTow);

    }// 生成随机字符串public function get_random($len,$chars)
    {$hash = "";$max = strlen($chars) - 1;for ($i=0; $i < $len; $i++) { $hash .= $chars[mt_rand(0,$max)];
        }return $hash;
    }
PHP 8.5.5 PHP 8.5.5 是 PHP 8.5 分支的维护更新版本。该版本延续了“小步快跑”的迭代逻辑,通过深度错误修复、底层性能微调以及安全加固,旨在为开发者提供一个更健壮、更高效的运行环境。该版本严格遵守语义化版本规范,不包含破坏性变更。 下载

相关文章