Laravel对其他领域进行排序

时间:2016-12-19 03:54:06

标签: php laravel collections eloquent usort

我明白了:

$companies = Company::all();

foreach($companies as $company)
{
    $company->distance = distance(); // a float type. My custom field.
}

$companies->sort(function ($a, $b){
            return strcmp($a->distance, $b->distance);
        })->values()->all();

我也尝试过: $companies->sortBy('distance')

以及其他一些不起作用的方式。

任何人都知道如何做到这一点?感谢

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

$companies = Company::all()->toArray();

foreach($companies as $key => $company)
{
     $distance[$key] = $company["distance"] = distance();
}

//now do a multisort on your distance array

 array_multisort($distance, SORT_ASC, $data);

有关详细信息,请参阅http://php.net/manual/en/function.array-multisort.php

答案 1 :(得分:0)

好的,我明白了。

$sorted = $companies->sortBy('distance');
$sorted->values()->all();

$companies = $sorted;

我猜它在排序时需要一个缓冲区。