Skip to content

Instantly share code, notes, and snippets.

@kevinruscoe
Created July 29, 2019 16:46
Show Gist options
  • Select an option

  • Save kevinruscoe/61c414f7ce0102856d45d0b0130f9038 to your computer and use it in GitHub Desktop.

Select an option

Save kevinruscoe/61c414f7ce0102856d45d0b0130f9038 to your computer and use it in GitHub Desktop.

Revisions

  1. Kevin Ruscoe revised this gist Jul 29, 2019. No changes.
  2. Kevin Ruscoe created this gist Jul 29, 2019.
    22 changes: 22 additions & 0 deletions sortWithPreference.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    Collection::macro(
    'sortWithPreference',
    function ($preference = [], $key = 'id') {
    return $this->sort(
    function ($a, $b) use ($preference, $key) {

    $a = array_search(is_array($a) ? $a[$key] : $a->$key, $preference);
    $b = array_search(is_array($b) ? $b[$key] : $b->$key, $preference);

    if ($a === false && $b === false) {
    return 0;
    } elseif ($a === false) {
    return 1;
    } elseif ($b === false) {
    return -1;
    }

    return $a - $b;
    }
    );
    }
    );