sphinx搜索封装成函数php
来源:原创
时间:2017-05-18
作者:脚本小站
分类:PHP
/** * sphinx搜索 * @param string $word 搜索的词 * @param int $id 要去掉的ID * @param int $number 取出的数目 * @return array $list 数据列表 */ function sphinx_search($word,$id,$number = 10,$heightlight = false){ if($word) { $word = str_replace(array(',',',','.','。','(',')','(',')','、','~','-'),' ',$word); $sphinx = new \SphinxClient (); $sphinx->SetServer ( '127.0.0.1', 9312); $sphinx->SetConnectTimeout ( 3 ); $sphinx->SetArrayResult ( true ); $sphinx->SetMatchMode ( SPH_MATCH_ANY ); $sphinx->SetSortMode ( SPH_SORT_RELEVANCE ); $sphinx->SetLimits(0,$number); $result = $sphinx->Query ( $word, 'article' ); if($result['total'] > 0) { // 查询出结果 $array = array_column($result['matches'],'id'); if($id){ unset($array[array_search($id , $array)]); } if(empty($array)){ return false; } $where['id'] = array('in',$array); $list = M('article')->field('id,title,img_url,atime')->where($where)->select(); // 装饰结果集 $title = array_column($list,'title'); if($heightlight){ $title = $sphinx->BuildExcerpts($title,'article_zhuqiyang',$word,array( 'before_match' => '<font class="c_red bold">', 'after_match' => '</font>' )); } $weight = array_column($result['matches'],'weight','id'); $list_count = count($list); for ($i = 0; $i < $list_count; $i++){ $list[$i]['title'] = $title[$i]; $list[$i]['weight'] = $weight[$list[$i]['id']]; } usort($list, function($a, $b){ $aw = $a['weight']; $bw = $b['weight']; $aa = $a['atime']; $ba = $b['atime']; if($aw == $bw){ if($aa == $ba){ return 0; } return ($aa < $ba) ? 1 : -1; } return ($aw < $bw) ? 1 : -1; }); return $list; } return false; } return false; }