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

我创建了一个搜索框,在 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"}


慕田峪7331174
浏览 151回答 2
2回答

扬帆大鱼

您可以使用 Php 函数levenshtein来衡量您的搜索词与给定字符串的相似程度。对于多维数组中的每个项目,您可以使用 levenshtein 函数计算相似度。相似度可以与原始字符串一起存储在一个数组中。然后可以对数组进行排序以获得排序的搜索结果。可以使用以下代码:function GetSortedSearchResults($options, $search_term) {&nbsp; &nbsp; $sorted_results = array();&nbsp; &nbsp; for ($count = 0; $count < count($options); $count++) {&nbsp; &nbsp; &nbsp; &nbsp; $similarity = levenshtein($options["label"], $search_term);&nbsp; &nbsp; &nbsp; &nbsp; $sorted_results[$similarity] = $options["label"];&nbsp; &nbsp; }&nbsp; &nbsp; ksort($sorted_results);&nbsp; &nbsp; return array_values($sorted_results);}

交互式爱情

function&nbsp;searchForId&nbsp;($id, $array) {foreach ($array as $key => $val) {if ($val['label'] === $id) {return $key;}}return null;}&nbsp;$ 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;
打开App,查看更多内容
随时随地看视频慕课网APP