Illuminate\Support\Collection::sortBy PHP Method

sortBy() public method

Sort the collection using the given callback.
public sortBy ( callable | string $callback, integer $options = SORT_REGULAR, boolean $descending = false ) : static
$callback callable | string
$options integer
$descending boolean
return static
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
    {
        $results = [];
        $callback = $this->valueRetriever($callback);
        // First we will loop through the items and get the comparator from a callback
        // function which we were given. Then, we will sort the returned values and
        // and grab the corresponding values for the sorted keys from this array.
        foreach ($this->items as $key => $value) {
            $results[$key] = $callback($value, $key);
        }
        $descending ? arsort($results, $options) : asort($results, $options);
        // Once we have sorted all of the keys in the array, we will loop through them
        // and grab the corresponding model so we can set the underlying items list
        // to the sorted version. Then we'll just return the collection instance.
        foreach (array_keys($results) as $key) {
            $results[$key] = $this->items[$key];
        }
        return new static($results);
    }

Usage Example

Exemplo n.º 1
0
 /**
  * @return Collection
  */
 public function getCategories() : Collection
 {
     $set = $this->categories->sortBy(function (CategoryModel $category) {
         return $category->spent;
     });
     return $set;
 }
All Usage Examples Of Illuminate\Support\Collection::sortBy