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

$row を $count の値で並べ替える必要があると思いますが、これを行う方法がわかりません。誰でも構文を手伝ってもらえますか?

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 に答える