入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

sphinx 根据字段在字段内搜索

创建时间:2016-07-28 投稿人: 浏览次数:2562

控制器

<?php
namespace appcontrollers;

use Yii;
use yiiwebController;
use appmodelsSphinx_much_search;
use SphinxClient;
class SearchController extends Controller
{
	public $enableCsrfValidation = false;
	public function actionLogin()
	{
		$db=new Sphinx_much_search;
		$a=$db->find()->asArray()->all();
		return $this->renderPartial("login");
	}
	public function actionSearch()
	{
		$field=yii::$app->request->post("field");
		$zhi=yii::$app->request->post("zhi");
		$sphinx= new SphinxClient();
		$sphinx->SetServer("127.0.0.1",9312);
		//将查询看作一个Sphinx内部查询语言的表达式
		$sphinx->SetMatchMode ( SPH_MATCH_EXTENDED2 );
		//@符号屏蔽错误  第一个参数中 $filed是字段名 $zhi是你要在这个字段中搜索的值  第二个参数是规则
		$res=$sphinx->Query("@".$field." ".$zhi,"mysql");
		// array_keys是获取数组中的键(获取到的是一个数组)  然后将数组转换成字符串
		$id=implode(",",array_keys($res["matches"]));
		$val=Sphinx_much_search::find()->where("id in ($id)")->asArray()->All();
		//print_r($val);die;
		foreach ($val as $k =>$v) 
		{
			$val[$k]["title"]=str_replace($zhi,"<font color="red">$zhi</font>",$v["title"]);
			$val[$k]["content"]=str_replace($zhi,"<font color="red">$zhi</font>",$v["content"]);
			$val[$k]["country"]=str_replace($zhi,"<font color="red">$zhi</font>",$v["country"]);
		}
		echo json_encode($val);
	}
}
?>

view

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="js/jq.js"></script>
</head>
<body>
	<table align="center">
		<tr>
			<td>搜索字段</td>
			<td>
				<select id="field">
					<option value="*">全部字段</option>
					<option value="title">标题</option>
					<option value="content">内容</option>
					<option value="country">国家</option>
				</select>
			</td>
			<td><input type="text" id="zhi"></td>
			<td><input type="submit" class="fun" value="搜索"></td>
		</tr>
		<tr id="lists">
			<td>标题</td>
			<td>内容</td>
			<td>国家</td>
		</tr>
		<tr class="contents"></tr>
	</table>
</body>
</html>
<script>
	$(".fun").click(function(){
		var field=$("#field").val();
		var zhi=$("#zhi").val();
		$.post("?r=search/search",{"field":field,"zhi":zhi},function(msg){
			//alert(msg);
			var data=eval("("+msg+")");
			var tr="";
			for(i in data)
			{
				tr+="<tr class="contents">";
				tr+="<td>"+data[i].title+"</td>"
				tr+="<td>"+data[i].content+"</td>"
				tr+="<td>"+data[i].country+"</td>"
				tr+="</tr>";
			}
			$(".contents").remove();
			 $("#lists").after(tr);
		})
	})
</script>


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。