我正在为我的网站构建基本搜索功能。意识到最有用的搜索显示的页面具有最多的术语计数,我编写了以下代码:
function search()
{
$this->page = preg_replace('/[^\w \"\']/i', '', trim($this->page));
preg_match_all('/"(.[^"]+)"|([\w]+)/i', $this->page, $terms);
$terms=array_unique($terms[0]); // scrub duplicate search terms
$tsql="SELECT reviewSummary, reviewFullText, game.gameName FROM review LEFT JOIN game ON review.gameID = game.gameID ";
$constraint="WHERE";
foreach ($terms as $term)
{
$term=str_replace('"','',$term);
$tsql.=" $constraint (reviewSummary LIKE '%".$term."%' OR reviewFullText LIKE '%".$term."%' OR game.gameName LIKE '%".$term."%')";
$constraint="AND";
}
$tsql .= "AND game.isPublished = 'y'";
$result = $this->sql->db_query($tsql);
if (mysql_num_rows($result)!=0)
{
while($row = mysql_fetch_array($result))
{
$gameName = stripslashes($row['gameName']);
$content = strip_tags($row['reviewFullText']) . ' ' . $row['reviewSummary'];
$counter = 0;
foreach($terms as $term)
{
$term=str_replace('"','',$term);
preg_match_all("/($term)/i", $content, $matches);
foreach($matches[0] as $m)
{
$counter++;
}
}
$found["Games"][$gameName]=$counter;
}
}
print_r($found);
}
效果很好。它不所做的是根据哪个匹配最多来排序结果。我不确定如何对生成的数组进行排序以实现此目的,任何人都可以帮忙吗?
答案 0 :(得分:1)
查看uasort(),它可以使用用户定义的比较函数对关联数组进行排序。这样的事情应该做到......
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
uasort($found["Games"], 'cmp');