很难解释,但我需要一些帮助。假设有4根弦$query = 'google awesome';
,$result1 = 'google is cool';
,$result1 = 'google is awesome';
,和$result3 = 'other page';
.
假设我使用PHP的similar_text();
, $result1
相似度为60%,$result2
相似度为70%,$result3
相似度为5%。
如何按照从高到低的顺序回显它们。请注意,我使用了超过3个字符串,我只是使用foreach();
回显结果。
编辑:这是我的代码。
if(isset($_GET['q'])) {
$results = file(__DIR__ . '/data/urls.txt');
$query = $_GET['q'];
foreach($results as $result) {
$explode = explode('::', $result);
$site = $explode[0];
$title = $explode[1];
/* if $query = similar to $title, echo ordered by similarity. */
}
}
我建议您将所有字符串存储在数组中,并使用用户定义的比较函数,如ussort ()
这个解决方案将允许具有相同相似度排名的$results不相互覆盖。在这一点上,他们是先到先得的。
$query = 'google awesome';
$results = array('google is cool', 'google is awesome','other page');
foreach ($results as $result) {
$rank = similar_text($query,$result);
$rankings[$rank][] = $result;
}
krsort($rankings);
PHP有usort
函数来创建您自己的比较函数。直接从文档:
<?php
$ref = "some ref string";
function cmp($a, $b)
{
global $ref;
return similar_text($ref, $a) - similar_text($ref, $b);
}
$a = array("one", "two", "three");
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value'n";
}
?>
请注意,这可能非常低效,因为每个字符串计算similar_text
不止一次。
例如,您可以构建一个数组,其中包含结果和文本,然后对数组进行排序并打印。
if(isset($_GET['q'])) {
$results = explode("'n",file_get_contents(__DIR__ . '/data/urls.txt')); // i assume all url is in a new line
$query = $_GET['q'];
$similarity = array();
$map = array();
foreach($results as $result) {
list($site,$title) = explode('::', $result);
$similarity[$site] = similar_text($title,$query); //calculate similari by title for sites 0 is similar bigger is not realy similar
$map[$site] = $title;
}
asort($similarity,SORT_NUMERIC); //sort the results
$limit = 10;
foreach($similarity as $site=>$sim){
print "<a href='{$site}'>{$map[$site]}</a>({$sim} % differnece what you need)<br/>";
if( --$limit < 1) break;
}
}
应该阅读的链接:
http://www.php.net/manual/en/function.arsort.php http://www.php.net/manual/en/function.each.php http://www.php.net/manual/en/function.list.php