php实现搜索类封装示例
程序员文章站
2024-04-01 23:54:28
本文为大家分享了php实现搜索类封装示例,供大家参考,具体内容如下
本文为大家分享了php实现搜索类封装示例,供大家参考,具体内容如下
<?php /** * soclass.php * 索引与搜索类 */ class soclass { private $_xindex; private $_xsearch; private $_project; public function __construct($project){ //载入引导文件 require_once 'lib/xs.php'; //初始化 $xs = new xs($project); $this->_project = $project; $this->_xindex = $xs->index; $this->_xsearch = $xs->search; $this->_xsearch->setcharset('utf-8'); } public function query($keyword,$row=20,$jnum=0){ $xs = new xs($this->_project); $xs->search->setfuzzy(); $xs->search->setautosynonyms(); $xs->search->setquery($keyword); //支持同义词搜索,默认打开 $xs->search->setlimit($row, $jnum); //设置返回结果最多为 5 条,并跳过前 10 条 $docs = $xs->search->search(); //执行搜索,将搜索结果文档保存在 $docs 数组中 $count = $xs->search->count(); //获取搜索结果的匹配总数估算值 if($count){ $data = array(); foreach ($docs as $key=>$doc){ $data[$key]['pid'] = $doc->pid; $data[$key]['nid'] = $doc->nid; $data[$key]['category'] = $doc->category; $data[$key]['url'] = $doc->url; $data[$key]['name'] = $xs->search->highlight(htmlspecialchars($doc->name)); $data[$key]['message'] = $xs->search->highlight(htmlspecialchars($doc->message)); } return array('data'=>$data,'count'=>$count); } return array(); } public function hotword($num,$type='lastnum'){ return $this->_xsearch->gethotquery($num,$type); } public function expanded($keyword){ return $this->_xsearch->getexpandedquery($keyword); } public function lastcount(){ return $this->_xsearch->getlastcount(); } public function index($data,$update=0){ // 创建文档对象 $doc = new xsdocument; $doc->setfields($data); // 添加或更新到索引数据库中 if(!$update){ $this->_xindex->add($doc); }else{ $this->_xindex->update($doc); } } public function delete($idarray){ //删除索引(主键删除array('1','2','3')) $this->_xindex->del($idarray); } public function addsynonym($word1,$word2){ $this->_xindex->addsynonym($word1,$word2); } public function clearindex(){ $this->_xindex->clean(); } } ?>
以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。