情景: 我們平臺有好多游戲, 運(yùn)營的同事在查詢某一款游戲的時候, 目前使用的是html的select下拉列表的展現(xiàn)形式, 運(yùn)營的同事得一個個去找,然后選中,耗時又費(fèi)眼
效果: 輸入"三國"或者"國三", 將自動列出所有包含"三國"的游戲名字, 輸入不限順序; 例如輸入"殺三國",仍然會將"三國殺"這款游戲找出來
實(shí)現(xiàn): 我用redis的集合+PHP的array_intersect()和mb系列函數(shù), 實(shí)現(xiàn)了一個超迷你的全文檢索功能
原理: (大道不過兩三言,說穿不值一文錢,哈哈)
1、將所有的游戲名字讀出來,拆分成單個漢字
2、 將這些漢字作為redis集合的鍵,寫入redis,每個集合里的值是所有那些游戲名字中包含此漢字的游戲的id
3、當(dāng)用戶輸入文字的時候通過ajax異步請求,將用戶輸入傳給PHP
4、將輸入的文字拆分成單個漢字, 分別找到這些漢字在redis中的集合值
5、取出來,求交集,就找到了同時包含這幾個漢字的游戲的id
6、最后到數(shù)據(jù)庫里查出來相應(yīng)的游戲信息即可
缺點(diǎn): 刪除數(shù)據(jù)不方便
PHP寫入redis和檢索的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
//自動補(bǔ)全 //不限輸入漢字的前后順序: 輸入"國三殺" => 輸出 "三國殺" function getAutoComplate() { //$word = $this->input->post('word'); $word = '三國' ; if ( empty ( $word )) { exit ( '0' ); } $intWordLength = mb_strlen( $word , 'UTF-8' ); $this ->load->library( 'iredis' ); if (1 == $intWordLength ) { $arrGid = $this ->iredis->getAutoComplate( $word ); } else { $arrGid = array (); for ( $i =0; $i < $intWordLength ; $i ++) { $strOne = mb_substr( $word , $i , 1, 'UTF-8' ); $arrGidTmp = $this ->iredis->getAutoComplate( $strOne ); $arrGid = empty ( $arrGid ) ? $arrGidTmp : array_intersect ( $arrGid , $arrGidTmp ); //求交集,因?yàn)閭魅氲膮?shù)個數(shù)不確定,因此不能直接求交集 } } $arrGame = $this ->gamemodel->getGameNameForAutoComplate( $arrGid ); // var_dump($arrGame);exit; $jsonGame = json_encode( $arrGame ); exit ( $jsonGame ); } //自動補(bǔ)全, 建立索引 function setAutoComplate() { $arrGame = $this ->gamemodel->getAllGameNameForAutoComplate(); $arrIndex = array (); foreach ( $arrGame as $gid => $gname ) { $intGnameLength = mb_strlen( $gname , 'UTF-8' ); for ( $i =0; $i < $intGnameLength ; $i ++) { $strOne = mb_substr( $gname , $i , 1, 'UTF-8' ); $arrIndex [ $strOne ][] = $gid ; } } $this ->load->library( 'iredis' ); foreach ( $arrIndex as $word => $arrGid ) { foreach ( $arrGid as $gid ) { $this ->iredis->setAutoComplate( $word , $gid ); } } } |
操作redis的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//自動補(bǔ)全功能 public function setAutoComplate( $key , $value ) { $youxikey = 'youxi_' . $key ; $this ->sAdd( $youxikey , $value ); } //自動補(bǔ)全功能 public function getAutoComplate( $key ) { $youxikey = 'youxi_' . $key ; return $this ->sMembers( $youxikey ); } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。