PHP调用Sphinx类API
最近TP5的项目用到了sphinx,sphinx如何安装配置百度都有,但是如何用php调用sphinx第三方,网上能直接使用的并不多,所以做了一个简单的可以直接使用的调用sphinx API的类,直接上代码
<?php
namespace Sphinx;
/**
* sphinx公共查询类
* @author 五个A的猪
* @version 1.0 版本号
*/
class Sphinx
{
/**
*sphinx 查询
*
* @access public
* @param string $ip 服务器ip
* @param string $name 查询sphinx名称
* @param array $where 查询条件:数组传参,单字段多数据传$where['test']=array(1,2,3);
* @param array $where['between'] 查询在字段值在某两个值之间参数,$where['between']['test'] = array(1,10);
* @param int $page 分页
* @param int $return_type aid返回类型:默认数组,1为字符串
* @param string $wherelogic 查询条件逻辑符号 & 和 |
* @param string $whereconn 查询条件连接符号 空格 和 =
* @param string $page_count 每页显示的数量
* @return array 返回类型
*/
public function sphinx_search($ip='',$name='',$where=array(),$page='',$return_type=0,$wherelogic="&",$whereconn=' ',$page_count=50){
$cl = new \sphinx\SphinxClient();
$cl->SetServer ($ip, 9312);
$cl->SetMatchMode (SPH_MATCH_EXTENDED2);//默认模式
$cl->SetSortMode (SPH_SORT_EXTENDED,"@id DESC");
if(!empty($page))
{
$page=$page-1;
}
if(empty($page_count))$page_count=50;
$pages=$page*$page_count;
$cl->SetLimits($pages,$page_count,500000);
if(!empty($where['between'])){
foreach($where['between'] as $k=>$v){
$cl->SetFilterRange($k,$v[0],$v[1]);
}
}
$select = $this->where($where,$wherelogic,$whereconn);
$result = $cl->Query($select,$name);
if($result['total']==0){
return false;
}
$data = array();
$data['id'] = array();
$data["total"] = 0;
if (!empty($result['matches'])){
if($return_type==1){//返回字符串id
$ids=array_keys($result['matches']);
$data['id']=implode(',',$ids);
}else{//返回数组aid
foreach($result['matches'] as $k=>$v){
$data['id'][] = $k;
}
}
$data["total"]=intval($result["total_found"])?intval($result["total_found"]):0;
$data["current_page"]=$page?$page:1;
$data["last_page"]=ceil($data["total"]/$page_count);
}
return $data;
}
public function where($where=array(),$wherelogic='&',$whereconn=' '){
$str = '';
foreach($where as $k=>$v){
if($k !== 'between'){
if(is_array($v)){
$is_first = false;
foreach($v as $key){
$or_and = $is_first?'|':'&';
$str .= $or_and.'@'.$k.$whereconn.$key;
$is_first = true;
}
}else{
if(!empty($v)){
$str .= $wherelogic.'@'.$k.$whereconn.$v;
}
}
}
}
$frist = substr($str, 0, 1 );
if($frist!='@'){
$str = substr($str,1,strlen($str));
}
return $str;
}
}
这个TP5和TP6都是亲测可用的,需要注意,引入sphinx第三方路径不要写错