我知道一定有这样的库,但我要做的是传入一个字符串数组和一个搜索字符串,并让它根据它与搜索字符串的相关程度对该数组进行排序。
我一直在苦苦思索如何用谷歌来解决这个问题,有人给我指出了正确的方向吗?
最好是用php或其它服务器端语言编写。
发布于 2012-12-31 09:04:46
我真的不知道你说的“启蒙”是什么意思..
但是,如果您希望根据搜索字符串找到最佳字符串,则可以使用Levenshtein算法。它计算两个字符串之间“距离”。
更多信息请点击这里:http://php.net/manual/fr/function.levenshtein.php
发布于 2015-09-04 16:47:09
这有点棘手,我不能用英语解释,所以我只能向你展示一个有效的代码。如果你有问题,你可以问。
<!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>https://stackoverflow.com/questions/14096281
复制相似问题