项目中我们经常会遇到根据关键字从文章的标题和内容搜索这样的需求,搜索的结果标题中含有关键字的数据要排在前面,内容含有关键字的数据排在后面,本文实现了一种方式。
function getData($page, $key){
$limit = 20;
$start = (intval($page) - 1) * $limit;
$titleSql = "select * from news where title like '%{$key}%' order by id desc limit $start, $limit";
$titleArray = mysql_query($titleArray, $conn);
$resultArray = $titleArray;
$count = count($resultArray);
if($count < $limit){
$start = $start + $count;
$limit = $limit - $count;
$contentSql = "select * from news where title not like '%{$key}%' and content like '%{$key}%' order by id desc limit $start, $limit";
$contentArray = mysql_query($contentSql, $conn);
foreach ($contentArray as $car){
$resultArray[] = $car;
}
}
return $resultArray;
}
function getData($page, $key){
$limit = 20;
$start = (intval($page) - 1) * $limit;
$titleSql = "select * from news where title like '%{$key}%' order by id desc limit $start, $limit";
$titleArray = mysql_query($titleArray, $conn);
$resultArray = $titleArray;
$count = count($resultArray);
if($count < $limit){
$start = $start + $count;
$limit = $limit - $count;
$contentSql = "select * from news where title not like '%{$key}%' and content like '%{$key}%' order by id desc limit $start, $limit";
$contentArray = mysql_query($contentSql, $conn);
foreach ($contentArray as $car){
$resultArray[] = $car;
}
}
return $resultArray;
}