douba9654 2018-10-25 11:49
浏览 32
已采纳

PHP - 排序和合并数组

I have a site with a search feature but am trying to improve the search for a fuzzy search.

So far what I've done is query all of my products and use similar_text() to see how close they are to the actual search term

I then create an array where the key is how similar it is and the value is the product id. I then sort this by the key/similarity.

$term = $_GET['search_term'];
$similar_array = [];
$sql = "SELECT * FROM products";
$stmt = DB::run($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $id = $row["pro_id"];
    $result = $row['product'];
    similar_text($term,$result,$similarity);
    $similar_array[$similarity][] = $id;
}
$closest_match = array_keys($similar_array);
rsort($closest_match);
$match_count = count($closest_match);
for($i=0; $i<$match_count; $i++){
    var_dump($similar_array[$closest_match[$i]]);
}

This gives me something like:

array (size=9)
  0 => int 28
  1 => int 1628
  2 => int 1665
  3 => int 1666
  4 => int 1667
  5 => int 1668
  6 => int 1669
  7 => int 1670
  8 => int 1671
C:\wamp64\www\V2\search.php:65:
array (size=2)
  0 => int 37
  1 => int 38
C:\wamp64\www\V2\search.php:65:
array (size=1)
  0 => int 481
C:\wamp64\www\V2\search.php:65:
array (size=3)
  0 => int 27
  1 => int 1009
  2 => int 1620
C:\wamp64\www\V2\search.php:65:
array (size=14)
  0 => int 30
  1 => int 104
  2 => int 131
  3 => int 134
  4 => int 168
  5 => int 169
  6 => int 170
  7 => int 557
  8 => int 1011
  9 => int 1014
  10 => int 1661
  11 => int 1662
  12 => int 1663
  13 => int 1664

I have a show_products() function that I just need to pass an array of ID's, so what I want to do now is take the multiple arrays of ID's from above and merge it in this specific order and then crop the array to a certain number so it won't have every product but will cut off after so many results.

Any help or suggestions with this would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • doushi3715 2018-10-25 12:05
    关注

    As per your query you can use follow below steps

    1. you merge all array by array_merge
    2. sort the array using rsort (highest merge come first);
    3. for display you can use array_slice or array_chunk
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里