回声字符串从最高到最低的相似度

Hard to explain, but I need some help. So I have, say 4 strings $query = 'google awesome';, $result1 = 'google is cool';, $result1 = 'google is awesome';, and $result3 = 'other page';.

Lets say I used PHP's similar_text();, and $result1 is 60% similar, $result2 is 70% similar and $result3 is 5% similar.

How do I echo them in order from highest to lowest. Note that I am using more that 3 strings, I just echo the results using foreach();.

EDIT: HERE is my piece of code.

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. */
    }
}

For exampe you could build an array, with the results and the text, than sort the array and print.

 if(isset($_GET['q'])) {
    $results = explode("
",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;
    }
}

Links that should be read:

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

I would suggest you store all strings in an array and use a user defined comparison function such as usort()

PHP has the usort function to create your own comparison function. Straight from the 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
";
}
?>

Note that this might be quite inefficient, as you are calculating similar_text more than once per string.

This solution will allow for $results with the same similarity ranking to not overwrite each other. They are listed first come first serve at that point.

$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);