Reputation: 649
I am trying to sort an object array by distance using usort. Here is my sort function:
private function sortDistance ($first, $next)
{
$d1 = $this->searchDistance[$first->zip];
$d2 = $this->searchDistance[$next->zip];
if ($d1 == $d2) {
return 0;
}
return ($d1 > $d2) ? +1 : -1;
}
Here is where I am calling usort:
return usort($searchResults->limit('5', $start)->get()->result(), array("Search", "sortDistance"));
For some reason, when I print_r the returned result, its only printing 1. Am I doing something wrong?
Thanks
Upvotes: 1
Views: 141
Reputation: 27356
Returning usort is returning 1 because the usort function has completed documentation. print_r() the array you just sorted, and you will see the sorted values :)
Working example:
$result = $searchResults->limit('5', $start)->get()->result();
usort($result, array("Search", "sortDistance"));
return $result;
Upvotes: 1
Reputation: 41448
Make your sort function static:
private static function sortDistance ($first, $next){ ...
Also, this will only work for sorting inside the Search class where the method is defined since it is private. To use it in the child classes make it protected, for use anywhere make it public.
Alternately, if you want to method it non-static and you're inside an instance of a Search object, you could make the method non static and call it like this:
return usort($searchResults->limit('5', $start)->get()->result(),
array($this, "sortDistance"));
Upvotes: 0