2

很难解释,但我需要一些帮助。所以我有 4 个字符串 $query = 'google awesome';, $result1 = 'google is cool';, $result1 = 'google is awesome';$result3 = 'other page';.

假设我使用了 PHP similar_text();,并且$result160% 相似,$result270% 相似,$result35% 相似。

我如何按照从高到低的顺序呼应它们。请注意,我使用了 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. */
    }
}
4

4 回答 4

1

我建议您将所有字符串存储在一个数组中并使用用户定义的比较函数,例如usort()

于 2013-03-10T17:45:59.437 回答
1

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每个字符串进行多次计算。

于 2013-03-10T17:48:51.667 回答
1

此解决方案将允许具有相同相似度排名的 $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);
于 2013-03-10T17:58:16.790 回答
0

例如,您可以使用结果和文本构建一个数组,然后对数组进行排序并打印。

 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

于 2013-03-10T17:51:32.843 回答