Welcome Guest, Not a member yet? Register   Sign In
Can anyone explain how this usort actually works

Hi all,

I have a function in one of my models that is working  exactly as I wanted it to, I just don't quite understand how it works.

I have read the php.net on usort but am still confounded by it. http://php.net/manual/en/function.usort.php
How does the comparison function help with sorting the entire data set given that it is just working out the difference between two indexes, the mysterious $a and $b?

usort($search_results,function($a, $b) {
    return $a['search_rank'] - $b['search_rank'];

My $search_results is an array created from searching lots of different tables and formatting and amalgamating the results (companies table, people table, projects table etc). The only thing I add is what I call a search_rank which is really just a count of the characters before the search string is first found, using stripos(), so a search for 'Mark' gives a score of 0 for a person named 'Mark Lee', or a score of 3 for the company 'Top Mark Ltd' as an example.

I then sort these rows by this search_rank in the search_results array with the above usort. (This is my attempt at adding a search relevance to the list).

But how is it working? It does work, amazingly well, but how?

The usort uses the callback function $a[]-$b[], but how is that helping usort to sort the entire data set? It is making no sense to me at all and really bugging me out. If anyone can shed any additional light on how usort is using that callback to sort my array I would be very interested to hear.

Thanks in advance for any input or feedback,

Best wishes,


Messages In This Thread
Can anyone explain how this usort actually works - by PaulD - 09-27-2015, 05:30 PM

Theme © iAndrew 2016 - Forum software by © MyBB