0

Possible Duplicate:
How to sort the results of this code?

I have made this code which allows a user to type in a search bar a question. This code then takes that question and looks for watching words with questions in my database. It then counts the number of matching words for each question. Once done it then displays the top 4 best matched questions depending on how many words match. However at the moment it displays these matches from lowest word match to highest word match (low-to-high) and I was it the other way around so that it displays the best match first (high-to-low). How do I do this in this code?

    <?php
        include("config.php");
        $search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
        $search_term = str_replace ("?", "", $search_term); //remove any question marks from string

        $array = explode(" ", $search_term); //Seperate user enterd data

        foreach ($array as $key=>$word) {
        $array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
        }

        $q = "SELECT * FROM posts WHERE  " . implode(' OR ', $array); //Query to select data with word matches
        $r = mysql_query($q);
        $count = 0; //counter to limit results shown
            while($row = mysql_fetch_assoc($r)){
            $thetitle = $row['title']; //result from query
            $thetitle = str_replace ("?", "", $thetitle);  //remove any question marks from string
            $title_array[] = $thetitle;  //creating array for query results
            $newarray = explode(" ", $search_term); //Seperate user enterd data again

            foreach($title_array as $key => $value) {
               $thenewarray = explode(" ", $value); //Seperate each result from query
               $wordmatch = array_diff_key($thenewarray, array_flip($newarray));
               $result = array_intersect($newarray, $wordmatch);
               $matchingwords = count($result); //Count the number of matching words from user entered data and the database query
            }
        if(mysql_num_rows($r)==0)//no result found{
            echo "<div id='search-status'>No result found!</div>";
        }
        else //result found
        {
        echo "<ul>";

        $title = $row['title'];
        if ($matchingwords >= 4){
        ?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> &nbsp; No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
                $count++;
                if ($count == 5) {break;
                }
                    }else{
                    }
                }
            echo "</ul>";
            }
?>
Community
  • 1
  • 1
Ben
  • 335
  • 3
  • 12
  • 1
    You should do this with pure SQL or something like lucene – Ron Aug 04 '12 at 07:48
  • Please don't use the `mysql_*` functions, they are no longer maintained and community has begun the [deprecation process](http://goo.gl/KJveJ) . Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you cannot decide, [this article](http://goo.gl/3gqF9) will help to choose. If you want to learn, [here is a good PDO-related tutorial](http://goo.gl/vFWnC). – vascowhite Aug 04 '12 at 07:54
  • Are you sure this code works? Seems to me the while() is never closed. Besides that, I would advise you to use better variablenames than "$newarray" and "$thenewarray". Also: you never declare $title_array as an array. This being said, I would reverse the displayed array. – JarroVGIT Aug 04 '12 at 07:55
  • I tried Luncene, I got completely lost, so thought id start from scratch with my own. Once iv got the sorting complete ill be done. – Ben Aug 04 '12 at 07:56
  • Djerro Neth - Yes the code works, iv tested it for loads of different searches, the only problem is that it displays the results low to high. Also I know about the variable names, I was in a rush to get it done so just gave them stupid names, once its complete ill go through it fully commenting and changing names to more meaningful things – Ben Aug 04 '12 at 08:00

4 Answers4

0

If you have saved you data in an array you can simply reverse it by using http://www.php.net/manual/en/function.array-reverse.php

Otherwise there are some sort functions http://php.net/manual/en/function.sort.php

Niels
  • 1,513
  • 3
  • 20
  • 29
0

I think you have problem in sorting an array.

If you have an array, sorting is not a matter.

Having different types of sorting found in php.

arsort()

Sort an array in reverse order and maintain index association

http://www.php.net/manual/en/function.asort.php

You can use this array function or let me know your questions briefly.

Karthi
  • 1
  • 1
0

you can write a own filter function

// sorts an array by direction
function arr_sort($arr, $index, $direction='asc')
{
    $i_tab = array();
    foreach ($arr as $key => $ele)
    {
        $i_tab[$key] = $arr[$key][$index];
    }
    $sort = 'asort';
    if (strtolower($direction) == 'desc')
    {
        $sort = 'arsort';
    }
    $sort($i_tab);
    $n_ar = array();
    foreach ($i_tab as $key => $ele)
    {
          array_push($n_ar, $arr[$key]);
    }
    return($n_ar);
}

for example you have an array $arr = array('key' => 'value', 'key2' => 'value');

you can now sort by key2 asc with

$arr = arr_sort($old_arr, 'key2', 'desc');

so you can put the total count of matching words into your array as a node for any entry and filter it by it descending

Ello
  • 907
  • 1
  • 15
  • 33
0

note this requires Mysql version 4+

A fulltext sql query returns values based on relevance.

Example:

SELECT *, MATCH (title)
AGAINST ('$search_term' IN NATURAL LANGUAGE MODE) AS score
FROM posts;

This is how you would implement it

$q = "SELECT *,MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) AS relevancy FROM
posts WHERE MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) ORDER BY
relevancy DESC";

This will return the posts in order by relevancy. May need to remove the '' around $search_term but you can figure that out with testing.

Please read up on Fulltext sql queries and the match() function. It is all clearly documented.

Branden S. Smith
  • 1,161
  • 7
  • 13
  • but how do I put this into my code. Iv tried changing my while loop with this but it doesnt work. How do I embed this into my code or where do I embed it? – Ben Aug 04 '12 at 08:18