我知道某处必须有一个库,但我想做的是传入一个字符串数组和一个搜索字符串,并让它按照与搜索字符串的相关程度对数组进行排序。
我一直很难弄清楚要谷歌来解决这个问题,有人指出我正确的方向吗?
最好使用 php 或其他服务器端语言
我真的不知道你所说的'revelant'是什么意思..
但是,如果您想根据搜索字符串找到最佳字符串,则可以使用 Levenshtein 算法。它计算两个字符串之间的“距离”。
更多信息在这里: http: //php.net/manual/fr/function.levenshtein.php
这有点棘手,我无法用英语真正解释,所以我只需要向您展示一个工作代码。如果你有问题,你可以问。
<!DOCTYPE html>
<head>
<title>Search Array</title>
<script>
//so let's set an array of values we will be searching
function searchArray(dis) {
var bigContent = new Array('Jesus loves you','Angle','God in Heaven','Bala','Overcomer','Be born again','Adesuwa','Heaven is real','James','Apple','John the baptist');//this is the array that serves as your database
var searchi = dis.value, result = Array();
searchi = searchi.toLowerCase();
//order the array alphabetically
bigContent = bigContent.sort();
var content;
if(searchi !='') {
//Define the arrays for initial pre-storage
var keys = new Array(), contentArray = new Array();
//Loop through the content array to search for all occurence of string
for(var i=0;i<bigContent.length;i++) {
content = bigContent[i].toLowerCase();
if(content.indexOf(searchi) > -1) {//found the search in this value
//get the position of the search string in content
var pos = content.indexOf(searchi);
//make position the key for your content array
if(contentArray[pos]) {//check if this position has already been assigned to a content
//if yes, append this content.
contentArray[pos] += '[]'+bigContent[i];
} else {//else, set the content
contentArray[pos] = bigContent[i];
//only save the position the first time you find it, to avoid duplication
keys[keys.length] = pos;
}
}
}
//sort the key so it can order the values in ascending order(relevance)
keys = keys.sort();
//loop thru the key
for(var i=0;i<keys.length;i++) {
var key = keys[i];//remember the value of "var key" is the key for contentArray value
if(contentArray[key]) {//just to be sure it's ther
var thisContent = contentArray[key];
//check if the content has more than 1 value
if(thisContent.indexOf('[]') < 0) {//if it doesn't
result[result.length] = contentArray[key];
} else {//if it does
//convert content into array
var thisContentAr = thisContent.split('[]');
//Loop thru the array
for(var j=0;j<thisContentAr.length;j++) {
result[result.length] = thisContentAr[j];
}
}
}
}
}
document.getElementById('ov').innerHTML = '';
for(var i = 0; i<result.length;i++) {
document.getElementById('ov').innerHTML += '<div>'+result[i]+'</div>';
}
}
</script>
</head>
<body>
<div><input type="text" onkeyup="searchArray(this);" autofocus="autofocus" /></div>
<div id="ov"></div>
</body>
</html>