首頁 >後端開發 >php教程 >php封裝搜尋類別實例

php封裝搜尋類別實例

*文
*文原創
2017-12-29 19:02:441969瀏覽

本文主要為大家詳細介紹了php實作搜尋類別封裝範例,有興趣的朋友可以參考一下。希望對大家有幫助。

具體內容如下

<?php
/**
 * SoClass.php
 * 索引与搜索类 
*/
class SoClass {
  private $_xindex;
  private $_xsearch;
 
  private $_project;
 
  public function __construct($project){
 
    //载入引导文件
    require_once &#39;lib/XS.php&#39;;
    //初始化
    $xs = new XS($project); 
    $this->_project = $project;
    $this->_xindex = $xs->index; 
    $this->_xsearch = $xs->search;
    $this->_xsearch->setCharset(&#39;UTF-8&#39;);
  }
 
  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][&#39;pid&#39;] = $doc->pid;
        $data[$key][&#39;nid&#39;] = $doc->nid;
        $data[$key][&#39;category&#39;] = $doc->category;
        $data[$key][&#39;url&#39;] = $doc->url;
        $data[$key][&#39;name&#39;] = $xs->search->highlight(htmlspecialchars($doc->name));
        $data[$key][&#39;message&#39;] = $xs->search->highlight(htmlspecialchars($doc->message));
      }
      return array(&#39;data&#39;=>$data,&#39;count&#39;=>$count);
    }
    return array();
  }
 
  public function hotWord($num,$type=&#39;lastnum&#39;){
 
    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(&#39;1&#39;,&#39;2&#39;,&#39;3&#39;))
    $this->_xindex->del($idArray); 
  }
 
  public function addSynonym($word1,$word2){
    $this->_xindex->addSynonym($word1,$word2);
  }
 
  public function clearIndex(){
    $this->_xindex->clean();
  } 
} 
?>

相關推薦:

php 封裝gd 函式庫

php 類別與建構子詳解

#php 類別與物件全面了解

#

以上是php封裝搜尋類別實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn