Jump to content

Need help sorting an array


kyleabaker

Recommended Posts

Hey, I'm trying to make my own search page for my website and I have it gathering correct results exactly as it should, but I'd like to find a way to have it sort these results according to their relevance (makes mroe sense of course). As it is now, it is simply pulling them from my database newest-to-oldest. The array elements are compiled like this..

 

type_of_item.id_#_of_item.hits_for_item.data

 

..so you can see that I have them all seperated by periods, then to print the data I just get the length that it is from the left and echo it out. I have all of that working, but I need to find a way to sort my array by the 3rd period seperated part...the hits. I want the items with the most hits at the top. Anyone have any ideas or help? Thanks in advanced.

Link to comment
Share on other sites

What exactly is this line doing...

 

return $l[2] == $r[2] ? 0 : ($l[2] < $r[2] ? -1 : 1);

 

can anyone explain it? Cause I had my search echo out the number of hits for each item and I'm seeing the following list..

 

1

1

3

1

1

1

 

..and it should be..

 

3

1

1

1

1

1

 

...maybe it is comparing in the wrong place..? Not sure tho, I just don't understand what that line is checking exactly.

Link to comment
Share on other sites

So it seems to be sorting the array based off of the 3rd character in the list.

ie.

news.id.hits.data

screenshots.id.hits.data

 

sorts to..

 

screenshots.id.hits.data

news.id.hits.data

 

..i'm trying to figure out how to sort it by the value of hits, so i need to split by chr(46) and compare values.

 

so i finally fixed it by using this..

 

<?PHP
function sortByHits($l, $r) {
$l_exploded = explode(chr(46),$l);
$r_exploded = explode(chr(46),$r);
return $l_exploded[2] == $r_exploded[2] ? 0 : ($l_exploded[2] > $r_exploded[2] ? -1 : 1);
}
usort($searchresults, "sortByHits");
?>

 

thanks so much Glyde for the help! Don't laugh at my terrible variable names, hehe. ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.