【问题标题】:How to sort the results of this code?如何对这段代码的结果进行排序?
【发布时间】:2012-08-04 13:35:54
【问题描述】:

我正在创建一个允许用户输入问题的搜索功能,然后我的代码会将尽可能多的单词与我的 MySQL 数据库中已有的问题匹配,并根据单词的数量显示前 5 个结果在问题中匹配。

我使用count() 函数来计算匹配单词的数量,但是目前显示的结果显示为数据库中具有 50% 或更多单词匹配的前 5 个结果。我希望首先将结果显示为最高匹配,然后逐步降低数据库中的每个结果,但只显示前 5 个。 这是我的代码

<?php
    include("config.php");
    $search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
    $search_term = str_replace ("?", "", $search_term); //remove any question marks from string
    $search_count = str_word_count($search_term);  //count words of string entered by user
    $array = explode(" ", $search_term); //Seperate user enterd data

    foreach ($array as $key=>$word) {
        $array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
    }

    $q = "SELECT * FROM posts WHERE  " . implode(' OR ', $array); //Query to select data with word matches
    $r = mysql_query($q);
    $count = 0; //counter to limit results shown
    while($row = mysql_fetch_assoc($r)){
        $thetitle = $row['title']; //result from query
        $thetitle = str_replace ("?", "", $thetitle);  //remove any question marks from string
        $title_array[] = $thetitle;  //creating array for query results
        $newarray = explode(" ", $search_term); //Seperate user enterd data again
        foreach($title_array as $key => $value) {
            $thenewarray = explode(" ", $value); //Seperate each result from query
            $wordmatch = array_diff_key($thenewarray, array_flip($newarray));
            $result = array_intersect($newarray, $wordmatch);
            $matchingwords = count($result); //Count the number of matching words from
            //user entered data and the database query
        }

        if(mysql_num_rows($r)==0)//no result found
        {
            echo "<div id='search-status'>No result found!</div>";
        }
        else //result found
        {
            echo "<ul>";
            $title = $row['title'];
            $percentage = '.5'; //percentage to take of search word count
            $percent = $search_count - ($search_count * $percentage); //take percentage off word count
            if ($matchingwords >= $percent){

                ?>
            <li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> &nbsp; No. matching words: <?php echo $matchingwords; ?></i></a></li>
            <?php

                $count++;
                if ($count == 5) {break;
                }
            }else{
            }
        }
        echo "</ul>";
    }
?>

下图显示了当我在搜索栏中搜索“如何制作自己的网站”时发生的情况。我已经在数据库中有几个问题要测试,它们都是相似的问题,最后一个条目与我提出的问题完全匹配,但由于它目前将它们显示为前 5 个数学结果,它忽略了完全匹配。 这是该搜索的结果。

我添加了一些代码,显示每个问题中有多少单词匹配,以便您可以看到它的工作更好。巧合的是,它以升序显示数据库中的前 5 个匹配结果。

我需要添加什么代码来排列它,以便它首先显示整个数据库中最接近的匹配,然后是第二个最佳匹配,第三个等等...?

【问题讨论】:

  • 警告您的代码容易受到 sql 注入攻击!
  • 您愿意进一步解释一下 Daniel A. White 吗?
  • 您的代码正在从查询字符串中删除内容,但将其直接加入到查询中。
  • 是的,但它只将它加入到 WHERE 子句中,另外我还可以添加额外的代码来检查以确保只有字母和数字已输入到字符串中。但是谢谢你告诉我
  • 请不要使用mysql_* 函数编写新代码。它们不再维护,社区已经开始deprecation process。看到 red box 了吗?相反,您应该了解prepared statements 并使用PDOMySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is good tutorial.

标签: php search sorting


【解决方案1】:

您可以使用嵌套 SQL 查询,您可以在其中按计数排序,或者先将值加载到数组 php 数组,然后对数组进行排序。使用 SQL 非常高效 && 更快。

Multi Dimension Array Sorting

select column1, column2,..., LENGTH(titlecolumn) - LENGTH(REPLACE(titlecolumn, '$search term', '')) AS nummatchwords from posts where " . implode(' OR ', $array) order by nummatchwords;

【讨论】:

  • 您能否展示一个使用按计数排序的嵌套 SQL 查询的示例,我确实想到了这一点,但不知道该怎么做,也找不到任何有用的资源来解释它
  • sql 查询可能类似于我在答案中发布的内容:)
  • 在那个 sql 中,你还需要使用 LIMIT 5 作为最佳实践
  • 感谢 Robi,但有人帮我完成了另一篇文章,为我重写了页面,它完全符合我的要求。但是非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2014-01-08
  • 2021-06-29
  • 2014-09-14
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 2016-07-03
相关资源
最近更新 更多