Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8359093
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T11:01:58+00:00 2026-06-09T11:01:58+00:00

Possible Duplicate: How to sort the results of this code? Im making a search

  • 0

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

Im making a search feature which allows a user to search a question and it will show the top 5 best matching results by counting the number of matching words in the question.
Basically I want the order to show the best match first which would be the question with the highest amount of matching words.
Here is the code I have.

<?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
$search_count = str_word_count($search_term);  //count words of string entered by user
$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'];
        $percentage = '.5'; //percentage to take of search word count
        $percent = $search_count - ($search_count * $percentage); //take percentage off word count
        if ($matchingwords >= $percent){
        $finalarray = array($title => $matchingwords);

        foreach( $finalarray as $thetitle=>$countmatch ){


?>
    <li><a href="#"><?php echo $thetitle ?><i> &nbsp; <br />No. of matching words: <?php echo $countmatch; ?></i></a></li>
<?php


                }
                $count++;
        if ($count == 5) {break;
        }
                }else{



            }
    }
echo "</ul>";
}

?>

When you search something it will show something like this.

enter image description here

Iv put the number of matching words under each of the questions however they are not in order. It just shows the first 5 questions from the database that have a 50% word match. I want it to show the top 5 with the most amount of matching words.

What code would I need to add and where would I put it in order to do this?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T11:02:01+00:00Added an answer on June 9, 2026 at 11:02 am

    Here’s my take on your problem. A lot of things have been changed:

    • mysql_ functions replaced with PDO
    • usage of anonymous functions means PHP 5.3 is required
    • main logic has been restructured (it’s really hard to follow your result processing, so I might be missing something you need, for example the point of that $percentage)

    I realize this might look complicated, but I think that the sooner you learn modern practices (PDO, anonymous functions), the better off you will be.

    <?php
    /**
     * @param string $search_term word or space-separated list of words to search for
     * @param int $count
     * @return stdClass[] array of matching row objects
     */
    function find_matches($search_term, $count = 5) {
        $search_term = str_replace("?", "", $search_term);
        $search_term = trim($search_term);
        if(!strlen($search_term)) {
            return array();
        }
        $search_terms = explode(" ", $search_term);
    
        // build query with bind variables to avoid sql injection
        $params = array();
        $clauses = array();
    
        foreach ($search_terms as $key => $word) {
            $ident = ":choice" . intval($key);
            $clause = "`title` LIKE {$ident}";
            $clauses []= $clause;
            $params [$ident] = '%' . $word . '%';
        }
    
        // execute query
        $pdo = new PDO('connection_string');
        $q = "SELECT * FROM `posts` WHERE  " . implode(' OR ', $clauses);
        $query = $pdo->prepare($q);
        $query->execute($params);
        $rows = $query->fetchAll(PDO::FETCH_OBJ);
    
        // for each row, count matches
        foreach($rows as $row) {
            $the_title = $row->title;
            $the_title = str_replace("?", "", $the_title);
    
            $title_terms = explode(" ", $the_title);
            $result = array_intersect($search_terms, $title_terms);
            $row->matchcount = count($result);
        }
    
        // sort all rows by match count descending, rows with more matches come first
        usort($rows, function($row1, $row2) {
            return - ($row1->matchcount - $row2->matchcount);
        });
    
        return array_slice($rows, 0, $count);
    }
    ?>
    
    <?php
        $search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
        $best_matches = find_matches($search_term, 5);
    ?>
    
    <?php if(count($best_matches)): ?>
        <ul>
        <?php foreach($best_matches as $match): ?>
            <li><a href="#"><?php echo htmlspecialchars($match->title); ?><i> &nbsp; <br/>No. of matching words: <?php echo $match->matchcount; ?></i></a></li>
        <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <div id="search-status">No result found!</div>
    <?php endif; ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Sort list using stl sort function My question is can we sort
Possible Duplicate: oracle PL/SQL: sort rows I run this query: Select a.product, sum( case
Possible Duplicate: php sort array by sub-value I have a multidimensional array like the
Possible Duplicate: Natural Sort Order in C# I have a list with a lot
Possible Duplicate: mysql custom sort I have an array of IDs: $ids = array(5,
Possible Duplicate: how to sort by length of string followed by alphabetical order? I
Possible Duplicate: how to sort a multidemensional array by an inner key How to
Possible Duplicate: HTML5 local storage sort I am storing data into a localstorage using
Possible Duplicate: How to get the sort order in Delphi as in Windows Explorer?
Possible Duplicate: && operator in Javascript In the sample code of the ExtJS web

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.