You get a bonus - 1 coin for daily activity. Now you have 1 coin

Sort Laravel collection by array of ids

Practice



sometimes it's necessary to sort all elements of a collection by another array. moreover the ids may not belong to the collection's ids, this can be done using the following method

if the collection's id values are not present in the array of ids to sort by, then these ids will end up at the end of the sorted collection

/**
* @param \Illuminate\Support\Collection $collection
* @param array $sortByIds
* @return \Illuminate\Support\Collection
*/

function sortCollectionByArraysIds($collection, $sortByIds)
{
$idsOnThisNode = array_intersect($sortByIds, $collection->pluck('id')->toArray());
$idsSort = array_merge(
$ids ,
array_diff($collection->pluck('id')->toArray(), $ids)
);

$collection = $collection->sort(function ($modelCategory, $modelCategorySecond) use ($ids ) {
return (
array_search($modelCategorySecond->id, $ids ) >
array_search($modelCategory->id, $ids ))
? -1 : 1;

});
return $collection;
}

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)