2011-04-25 25 views
0

我试着做了一个小网站一个简单的搜索功能,并拥有最相关的项目在顶部排序和substr_count

$q = "SELECT * FROM pages as p WHERE p.content LIKE '%$searchparam%' OR p.title LIKE '%$searchparam%' LIMIT 500";  
$r = @mysqli_query ($dbc, $q); // Run the query. 
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { 

    $count = substr_count($row['content'], "$searchparam"); 

我猜我需要梳理$从$值排计数,但我不知道如何做到这一点。任何人都可以帮助我的语法?

回答

1

更好的解决方案是使用MySq'ls full text search功能,因为结果被返回排名,并且它可能比尝试自己编写结果更容易和更强大。你也可以看看其他搜索引擎,如狮身人面像。

但是,如果你想继续用你的方法,你应该这样做:

$results = array(); 
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { 
    $count = substr_count($row['content'], "$searchparam"); 
    //add the details you want to the array. You could also just add count 
    // to $row and add $row to $results 
    $results[] = array(
     'count' => $count, 
     'resultid' => $row['id'] 
    ); 
} 

//custom sort function that uses the count to order results  
function cmp($a, $b){ 
    if ($a['count'] == $b['count]) { 
     return 0; 
    } 
    return ($a > $b) ? -1 : 1; 
} 

//sort the array using the sort function 
usort($results, 'cmp'); 
+0

大多数我需要搜索的表的正使用InnoDB ... – aph107 2011-04-25 12:42:56