【问题标题】:How to sort multi-dimensional array with search option in PHP?如何在 PHP 中使用搜索选项对多维数组进行排序?
【发布时间】:2019-07-01 10:53:13
【问题描述】:

我已经创建了一个搜索框,并且在 keyup 事件中,我正在从其他文件中获取 json_encoded 数组,但我面临的问题是。例如。如果我输入“Melbourne” 它会在完全匹配之前显示“East Melbourne”和其他选项。我想先展示墨尔本,然后再展示东墨尔本、西墨尔本和其他选项。

我想用确切的搜索字符串对其进行排序。

The current array is like:
$response[] = array("category"=>'cat_name',"label"=>'East Melbourne');
$response[] = array("category"=>'cat_name',"label"=>'Melbourne');

Output:
{category: "City", label: "East Melbourne", value: "East Melbourne"}
{category: "City", label: "Melbourne", value: "Melbourne"}

【问题讨论】:

  • 您在数组中搜索的代码在哪里?
  • @Shujaat,感谢您的回复。实际上,我运行 SQL 查询以获取 ASCENDING ORDER 中的数据并获得如上所示的结果。现在我想将结果过滤为精确的 LABEL 匹配。
  • 您的示例显示与您解释的相反。 “墨尔本”必须在“东墨尔本”之前还是之后?你的代码在哪里?
  • @Toto -- 如果用户输入 Melbourne 关键字,它应该首先显示完全匹配的 Melbourne,然后在东墨尔本之后应该显示。

标签: php arrays wordpress sorting multidimensional-array


【解决方案1】:

您可以使用 Php 函数 levenshtein 来衡量您的搜索词与给定字符串的相似程度。对于多维数组中的每个项目,您可以使用 levenshtein 函数计算相似度。相似度可以与原始字符串一起存储在数组中。然后可以对数组进行排序以获得排序的搜索结果。可以使用以下代码:

function GetSortedSearchResults($options, $search_term) {

    $sorted_results = array();
    for ($count = 0; $count < count($options); $count++) {
        $similarity = levenshtein($options["label"], $search_term);
        $sorted_results[$similarity] = $options["label"];
    }

    ksort($sorted_results);

    return array_values($sorted_results);
}

【讨论】:

  • 这简直太完美了,我找到了解决方案。谢谢。
【解决方案2】:

function searchForId($id, $array) {foreach ($array as $key => $val) {if ($val['label'] === $id) {return $key;}}返回空值;} $response[] = array("category"=>'cat_name',"label"=>'East Melbourne');$response[] = array("category"=>'cat_name',"label"= >'Melbourne');$response[] = array("category"=>'cat_name',"label"=>'West Melbourne');$id = searchForId('Melbourne', $response);$newArr[] =$response[$id];unset($response[$id]);$newArr1=array_merge($newArr,$response);echo "";print_r($newArr1);exit;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多