首頁  >  文章  >  資料庫  >  怎麼用PHP+Redis來實現排行榜

怎麼用PHP+Redis來實現排行榜

PHPz
PHPz轉載
2023-05-31 13:46:06824瀏覽

透過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,&#39;abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ&#39;);            $this->redis->zadd($this->cachekey,$num,json_encode([&#39;name&#39;=>$str]));// 由大到小排序$dataOne = $this->redis->ZREVRANGE($this->cachekey, 0, -1, true);// 由小到大排序$dataTow = $this->redis->ZRANGE($this->cachekey, 0, -1, true);
        }echo "<pre class="brush:php;toolbar:false">";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+Redis來實現排行榜

#

以上是怎麼用PHP+Redis來實現排行榜的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除