Last active
February 29, 2024 19:24
-
-
Save nuernbergerA/a06f70fb521bd4163163676d6731a60d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\Illuminate\Support\Collection::macro('sortByList', function (iterable $orderList, ?string $property = null) { | |
return $this | |
->sortBy(function($item) use ($property, $orderList) { | |
$value = $item; | |
if (is_iterable($item)) { | |
$value = $item[$property]; | |
} | |
if (is_object($item)) { | |
$value = $item->$property; | |
} | |
$position = array_search($value, collect($orderList)->values()->toArray(), true); | |
return $position !== false ? $position : INF; | |
}); | |
}); | |
\Illuminate\Support\Collection::macro('sortKeyByList', function (iterable $orderList) { | |
return $this | |
->sortBy(function($item, $key) use ($orderList) { | |
$position = array_search($key, collect($orderList)->values()->toArray(), true); | |
return $position !== false ? $position : INF; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment