0

我试图为一个小网站做一个简单的搜索功能,并在顶部有最相关的项目

$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");

我猜我需要用 $count 中的值对 $row 进行排序,但我不知道该怎么做。任何人都可以帮我解决语法吗?

4

1 回答 1

1

更好的解决方案是使用MySq 的全文搜索功能,因为返回的结果是排名的,它可能比尝试自己编写更容易和更健壮。您还可以查看其他搜索引擎,例如 Sphinx。

但是,如果您想继续使用您的方法,您应该执行以下操作:

$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');
于 2011-04-25T12:41:05.030 回答