Php 如何一次在多个字段中搜索多个单词?
我正在编写一个搜索模块。我不知道我是否在一个好的方式,但我现在听起来不错,除了一点 使用下面的代码,我只能搜索一个单词Php 如何一次在多个字段中搜索多个单词?,php,mysql,cakephp,search-engine,cakephp-2.3,Php,Mysql,Cakephp,Search Engine,Cakephp 2.3,我正在编写一个搜索模块。我不知道我是否在一个好的方式,但我现在听起来不错,除了一点 使用下面的代码,我只能搜索一个单词 <?php class SearchesController extends AppController{ function index(){ if($this->request->is('put') || $this->request->is('post') ){ // Save the sen
<?php
class SearchesController extends AppController{
function index(){
if($this->request->is('put') || $this->request->is('post') ){
// Save the send data
$search = $this->request->data['Search']['key'];
//$nbWords = str_word_count($search);
/*
THIS DOES NOT WORKS
if($nbWords > 1){
$searchTerms = explode(' ', $search);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "Page.name LIKE '%$term%' AND Page.content LIKE '%$term%'";
}
}
}else{
$term = $search;
$searchTermBits[] = "Page.name LIKE '%$term%' AND Page.content LIKE '%$term%'";
}
*/
// SEARCH IN Pages TABLE
$this->loadModel('Page');
// SAVE THE RESULT IN
$d['pages'] = $this->Page->find('all', array(
'conditions' => array(
'online'=>'1',
'type'=>'page',
'created <= NOW()',
'id > 1',
'OR' => array(
//implode(' AND ', $searchTermBits)
'Page.name LIKE'=>'%'.$search.'%',
'Page.content LIKE'=>'%'.$search.'%'
)
),
'fields' => array('name','content','created','id','type')
));
//SEARCH IN Posts TABLE
$this->loadModel('Post');
$d['posts'] = $this->Post->find('all', array(
'conditions' => array(
'online'=>'1',
'type'=>'post',
'created <= NOW()',
'OR' => array(
'Post.name LIKE'=>'%'.$search.'%',
'Post.content LIKE'=>'%'.$search.'%'
)
),
'fields'=> array('name','content','created','id','type','slug')
));
// SEND THE VALUES TO THE VIEW
$this->set($d);
}else{
echo 'e';
}
}
}
让它能够搜索“名称”和“内容”几个词
谢谢你的帮助
干杯你可以试试这个:
'OR' => array(
'Post.name' IN ('name1', 'name2'),
'Post.content' IN ('content1', 'content2')
)
显然,您可以将值放入如下数组:
$name_arr = array();
$name_arr[] = 'name1';
$name_arr[] = 'name2';
及之后:
'OR' => array(
'Post.name' IN ($name_arr),
'Post.content' IN ('content1', 'content2')
)
更改$search变量
$search = $this->request->data['Search']['key'];
// if keywords "red car" then it will pass to your query %red%car%;
$search = str_replace(" ","%",$search);
现在,它将搜索同时包含两个单词的记录。如果要搜索多个用空格分隔的单词,可以这样做
$searches = explode(" ", $search);
foreach ($searches as $search) {
//put your search condition in here
}
你可以调查一下。如果正确设置索引,则可以运行以下查询:
根据文章中的“教程”选择id、匹配标题和正文 谢谢你,我要试一下:不要重新发明轮子,保持简单。
$searches = explode(" ", $search);
foreach ($searches as $search) {
//put your search condition in here
}