为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 PHP 中的搜索选项对多维数组进行排序?

如何使用 PHP 中的搜索选项对多维数组进行排序?

PHP
慕田峪7331174 2021-09-18 17:02:30
我创建了一个搜索框,在 keyup 事件中,我从其他文件中获取 json_encoded 数组,但我面临的问题是。例如。如果我输入“墨尔本”,它会在完全匹配之前显示“东墨尔本”和其他选项。我想先展示墨尔本,然后是东墨尔本、西墨尔本和其他选项。我想用确切的搜索字符串对其进行排序。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"}
查看完整描述

2 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您可以使用 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);

}


查看完整回答
反对 回复 2021-09-18
?
交互式爱情

TA贡献1712条经验 获得超3个赞

function searchForId ($id, $array) {foreach ($array as $key => $val) {if ($val['label'] === $id) {return $key;}}return null;} $ 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;


查看完整回答
反对 回复 2021-09-18
  • 2 回答
  • 0 关注
  • 150 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信