代码之家  ›  专栏  ›  技术社区  ›  Paddy Hallihan

PHP-排序和合并数组

  •  0
  • Paddy Hallihan  · 技术社区  · 7 年前

    到目前为止,我所做的是查询我的所有产品并使用 imilar_text()

    然后我创建一个数组,其中键是它的相似程度,值是产品id。

    $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]]);
    }
    

    这让我感觉到:

    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
    

    我有一个 show_products() 函数,我只需要传递一个ID的数组,所以我现在要做的是从上面取多个ID的数组,按这个特定的顺序合并,然后将数组裁剪到某个数字,这样它就不会有所有的乘积,而是在得到这么多结果后将其截断。

    1 回复  |  直到 7 年前
        1
  •  0
  •   bimal sharma    7 年前

    根据您的查询,您可以使用以下步骤

    1. 合并所有数组 array_merge
    2. 使用对数组排序 rsort
    3. 您可以使用 array_slice 或 array_chunk