編碼的世界 / 優質文選 / 文明

yii 框架 的sphinx類引入 使用 及 關鍵字標紅


2021年11月23日
-   

yii框架引入sphinx類 及使用
1.在yii框架 根目錄下建立 文件夾 sphinx
2.把sphinxapi.php放到sphinx文件中
3.在config/web.php文件中加入一句話
Yii::$classMap['SphinxClient']='@app/sphinx/sphinxapi.php';@
$ 4.控制器調用sphinx類
$sphinx= new SphinxClient();
5.鏈接sphinx
$sphinx->SetServer('127.0.0.1', 9312);@

6.設置查詢模式查詢出結果
//根據某個字段進行查詢模式
$sphinx->SetMatchMode ( SPH_MATCH_EXTENDED2 );
$result = $sphinx->query('@title 你好', "*");//‘title’ 字段名 ‘你好’關鍵字
//根據全部字段進行查詢
//$sphinx-> SetMatchMode(SPH_MATCH_ANY);//搜索
//$sphinx -> SetSortMode(SPH_SORT_EXTENDED, '@id desc'); //排序
//$result = $sphinx-> Query($name,"*");
7.根據查詢出的id查出數據庫中的數據@

$id=implode(',',array_keys($result['matches']));
$search=Search::find()->where('id in ('.$id.')')->asArray()->all();
print_r($search);

yii框架關鍵字標紅
8.運用sphinx裏的
BuildExcerpts屬性('從數據庫查詢出來的東西必須為一維數組','索引名字我這裏是 (mysal)','收索的關鍵字','標紅的一個方法,我這裏定義的是$opts')
9.具體的做法
//定義標紅方法
$opts = array('before_match'=>'<font style="font-weight:bold;color:red">','after_match'=>'</font>');
//循環標紅
foreach($search as $v){
$res=$sphinx->BuildExcerpts($v,'mysql','你好',$opts);// "mysql" 我的索引名 “你好”要標紅的關鍵字;
}
print_r($res);
這時你就會發現輸出的數組中關鍵字已經標紅了;

熱門文章