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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料