Skip to content
This repository was archived by the owner on May 12, 2022. It is now read-only.

Commit 40b2aff

Browse files
author
Nik Barham
committed
Adding function to sort a collection based on an already sorted list of ids
1 parent 66fa115 commit 40b2aff

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/Orm/Collection.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,25 @@ public function sort(callable $function)
268268
uasort($copy, $function);
269269
return new static($copy);
270270
}
271+
272+
/**
273+
* Return a new sorted Collection using the already ordered list of Ids
274+
* Only works for collections containing Model objects
275+
*
276+
* @param callable $function Callable to use to sort the array
277+
* @return self New Collection containing the sorted items
278+
*/
279+
public function sortById(array $listOfIds)
280+
{
281+
if (!$this->first() instanceof Model) {
282+
throw new Exception\BaseException('sortById can only be called on collections of Model objects');
283+
}
284+
$order = array_values($listOfIds);
285+
286+
return $this->sort(function ($a, $b) use ($order) {
287+
return array_search($b->id, $order) - array_search($a->id, $order);
288+
});
289+
}
271290

272291
/**
273292
* Return a new sorted Collection using provided sort function (through uasort() + strnatcasecmp())

0 commit comments

Comments
 (0)