dongwu3596 2018-11-21 10:03
浏览 35

too long

This question already has an answer here:

i have an array with the result of the search term. please take a look at blow code

$keyword = trim($_POST['keyword']);

$keyword = preg_replace('!\s+!', ' ', $keyword);
$words = explode(' ', $keyword);
$keyword = str_replace(" ","+",$keyword);
$query = "SELECT * FROM videos WHERE MATCH (video_name) AGAINST ('$keyword' IN BOOLEAN MODE)";

$q_result = mysql_query($query) or die (mysql_error());
if (mysql_num_rows ($q_result) != 0) {
    while ($row = mysql_fetch_assoc($q_result)) {
        $id = $row['id'];
        $video_name = $row['video_name'];
        $result[]= "$id $video_name";
    }
}
foreach($result as $res){
    echo "$res <br>";
}
}

it is working perfectly. but it is displaying the result in ascending order to id. what I want is if a row contains all or maximum keywords it should be the first element of the array.

let me explain further. suppose we have 3 rows id video_name 1 how to create php code. 2 php language scope in future. 3 the future of php.

if a user searches "PHP language scope in future" the array should be arranged by id 2,3,1

here is the output. as you can see query I have searched 3 words

out_put of my code

hope its clear

</div>
  • 写回答

1条回答 默认 最新

  • doulu3808 2018-11-21 10:53
    关注

    Frankly speaking this question is very similar to yours one as Nico Haase mentioned.

    In your case you could use the following query:

    SELECT videos.*,
           MATCH (video_name) AGAINST ('$keyword' IN BOOLEAN MODE) AS relevance
    FROM videos 
    WHERE MATCH (video_name) AGAINST ('$keyword' IN BOOLEAN MODE)
    ORDER BY relevance DESC
    

    Here you are going to use calculated value "relevance" that performs as "weight" of every row to order by it. The value will be in the form of number determining the weight. This weight will be higher when most of keywords are here and lower when lesser amount of keywords is presented.

    UPD: If you prefer to do a sort on the side of PHP not the side of database engine then you can check the function usort. It allows to define your own logic to sort an array of any structure. Personally me I prefer database side sorting in such a case.

    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装