排序和 substr_count

发布于 2024-11-03 15:23:21 字数 418 浏览 2 评论 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 进行排序,但我不确定如何执行此操作。谁能帮我解决语法问题吗?

Im trying to make a simple search function for a small site, and have the most relevant items at the top

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

I'm guessing I need to sort $row with the value from $count, but I'm not sure how to do this. Can anyone help me out with the syntax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮萍、无处依 2024-11-10 15:23:21

更好的解决方案是使用 MySq'ls 全文搜索 功能,因为结果是按排名返回的,并且它可能比尝试自己编写更容易、更健壮。您还可以查看其他搜索引擎,例如 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');

A better solution would be use use MySq'ls full text search capabilities, as the results are returned ranked and it is probably easier and more robust than trying to write it yourself. You could also look into other search engines like Sphinx.

However, if you wanted to continue with your method, you should do something like:

$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');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文