1

我正在尝试使用 usort 按距离对对象数组进行排序。这是我的排序功能:

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;
}

这是我调用 usort 的地方:

return usort($searchResults->limit('5', $start)->get()->result(), array("Search", "sortDistance"));

出于某种原因,当我 print_r 返回的结果时,它只打印 1。我做错了什么吗?

谢谢

4

2 回答 2

1

返回 usort 是返回 1 因为 usort 函数已完成文档。print_r() 你刚刚排序的数组,你会看到排序后的值 :)

工作示例:

$result = $searchResults->limit('5', $start)->get()->result();
usort($result, array("Search", "sortDistance"));
return $result;
于 2013-02-25T16:43:42.403 回答
0

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"));
于 2013-02-25T16:45:36.900 回答