我有一个InnoDB表,从中检索值并将其存储在PHP中的数组中。
现在我想根据搜索字符串中的匹配对数组进行排序。
例如:如果我搜索“你好吗”,它会将字符串拆分为单独的单词,如“hai”“how”“是”“you”,搜索后的结果必须如下:
[0] hai how are all people there
[1] how are things going
[2] are you coming
[3] how is sam
...
有没有什么方法可以单独根据基本的PHP函数对数组进行排序?
答案 0 :(得分:0)
$searchText = "hai how are you"; //eg: if there are multiple spaces between words
$searchText = preg_replace("(\s+)", " ", $searchText );
$searchArray =& split( " ", $searchText );
$text = array(0 => 'hai how are all people there',
1 => 'how are things going ',
2 => 'are you coming',
3 => 'how is sam',
4 => 'testing ggg');
foreach($text as $key=>$elt){
foreach($searchArray as $searchelt){
if(strpos($elt,$searchelt)!== FALSE){
$matches[] = $key; //just storing key to avoid memory wastage
break;
}
}
}
//print the matched string with help of stored keys
echo '<pre>matched string are as follows: ';
foreach ($matches as $key){
echo "<br>{$text[$key]}";
}
答案 1 :(得分:0)
也许是这样的:
$arrayToSort=array(); //define your array here
$query="hai how are you";
function compare($arrayMember1,$arrayMember2){
$a=similar_text($arrayMember1,$query);
$b=similar_text($arrayMember2,$query);
if($a>$b)return 1;
else return -1;
}
usort($arrayToSort,"compare");
查看php手册,了解有关similar_text和usort的内容。