Laravel sort on additional field

422 views Asked by At

I got this:

$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();

I've also tried: $companies->sortBy('distance')

And some other ways that didn't work.

Anyone has any idea on how to accomplish this? Thanks

2

There are 2 answers

0
Alice On BEST ANSWER

Okay, I figured it out.

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

$companies = $sorted;

I guess it needs a buffer when it sorts.

0
pseudoanime On

try the following code:

$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);

for more information, refer to http://php.net/manual/en/function.array-multisort.php