使用生成的数字对PHP结果进行排序

时间:2012-05-29 09:28:28

标签: php search

我已经整理了一个迷你搜索算法,根据他们输入的内容以及测试正文中的链接数量,垃圾词等因素为搜索结果分配分数。

不幸的是,我不知道如何根据生成此数字的顺序来排序结果。订购PHP的任何想法都会产生分配给它的“得分”?我应该补充一点,这个分数不是保存在数据库中,而是每次根据用户搜索的内容生成。

好的,所以这按顺序列出所有结果取决于使用的搜索词,我需要按“TotalScore”排序,但我无法弄清楚如何操作...

以下是代码:

$refType = $_GET["ref"];
$setLimit = $_GET["list"];

//CATCH & SECURE THE QUERY
$q = mysql_real_escape_string($_GET["q"]);

//SET LISTING VALUE IF CHOSEN, DEFAULT 10
if(!$setLimit || $setLimit == "0"){
$setLimit = "10";
} else {
$setLimit = $_GET["list"];
}

//GET NUMBER OF WORDS IN QUERY & RETURN ERROR IF MORE THAN 12

$searchTermCount = str_word_count($q);
if($searchTermCount > 12){
$searchLine = "";
$searchList = "Your search contained too many words! Please go back and try again, use less than 12 words to find what you are looking for.";
} else if($q == "" || !$q || $q == " "){
$searchLine = "";
$searchList = "You did not submit a search term! Please go back and enter your city into the search bar!";
} else {

$searchLine = "Your search for " . $q . " found the following results";

//PUT NEW ALGORITHM HERE

$findDetails = mysql_query("SELECT * FROM [TABLENAME] WHERE upper(city) like '%$q%' AND verified='1' OR upper(county) like '%$q' AND verified='1' OR upper(title) like '%$q%' AND verified='1' OR upper(intro) like '%$q%' AND verified='1' OR upper(content) like '%$q%' AND verified='1' ORDER BY datePosted DESC LIMIT $setLimit");
while($row = mysql_fetch_array($findDetails)){
    $adId = $row["id"];
    $adTitle = $row["title"];
    $adIntro = $row["intro"];
    $adCity = $row["city"];
    $adCounty = $row["county"];
    $adVerified = $row["verified"];
    $cutIntro = substr($adIntro, 0, 140);

    $numberOfResults = mysql_num_rows($findDetails);

    $findReviews = mysql_query("SELECT * FROM [TABLENAME2] WHERE adventureID='$adId'");
    $findReviews = mysql_num_rows($findReviews);

    $titleScore = "";
    $introScore = "";
    $contentScore = "";

    //CUT SEARCH TERM
    $qBreak = explode(" ", $q);
    foreach($qBreak as $qWord){ 
    $titleScore = $titleScore+substr_count($adTitle, $qWord);
    $introScore = $introScore+substr_count($adIntro, $qWord);
    $contentScore = $contentScore+substr_count($adContent, $qWord);
    }

    $totalScore = $titleScore+$introScore+$contentScore;

    $searchList .='
    <div style="width: 100%;" class="result' . $totalScore . '">
    ' . $adTitle . '<br />' . $adIntro . '<br /><br />' . $adContent . '
    <br /><br /><br />
    Total Score: ' . $totalScore . '<br />
    Title Score: ' . $titleScore . '<br />
    Intro Score: ' . $introScore . '<br />
    Content Score: ' . $contentScore . '<br /><br />
    </div>
    ';

}

}

1 个答案:

答案 0 :(得分:3)

查看usort功能。您为它提供了一个比较函数,它比较了数组的两个元素。编写一个回调函数应该很容易比较数组中两个元素的得分。