1

我有一个 InnoDB 表,从中检索值并将其存储在 PHP 的数组中。

现在我想按与搜索字符串中匹配项的相关性对数组进行排序。

eg:如果我搜索“hai how are you”,它会将字符串拆分为单独的单词,如“hai”“how”“are”“you”,搜索后的结果必须如下:

 [0] hai how are all people there

 [1] how are things going 

 [2] are you coming

 [3] how is sam

...

有什么方法可以仅通过基本 PHP 函数中的相关性对数组进行排序吗?

4

2 回答 2

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]}";    
}
于 2012-11-16T11:38:39.870 回答
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 的作用。

于 2012-11-16T11:39:15.653 回答