很难解释,但我需要一些帮助。
所以我有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. */
}
}
答案 0 :(得分:1)
我建议您将所有字符串存储在数组中并使用用户定义的比较函数,例如usort()
答案 1 :(得分:1)
PHP具有usort
函数来创建自己的比较函数。直接从docs:
<?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
次数不止一次。
答案 2 :(得分:1)
此解决方案将允许具有相同相似性排名的$结果不会相互覆盖。它们在那时被列为先到先得。
$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);
答案 3 :(得分: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