Yosymfony\Spress\Core\Support\ArrayWrapper::sortBy PHP Method

sortBy() public method

Sort the array sing the given callback.
public sortBy ( callable $callback, string $key = null, integer $options = SORT_REGULAR, boolean $isDescending = false ) : array
$callback callable Callback should be a function with the following signature: ```php function($key, $value) { // return $processedValue; } ```
$key string Element to sort using "dot" notation. You can to escape a dot in a key surrendering with brackets: "[.]"
$options integer See sort_flags at http://php.net/manual/es/function.sort.php
$isDescending boolean
return array
    public function sortBy(callable $callback, $key = null, $options = SORT_REGULAR, $isDescending = false)
    {
        $elements = [];
        $sourceElements = is_null($key) === true ? $this->array : $this->get($key);
        foreach ($sourceElements as $key => $value) {
            $elements[$key] = $callback($key, $value);
        }
        $isDescending ? arsort($elements, $options) : asort($elements, $options);
        foreach (array_keys($elements) as $key) {
            $elements[$key] = $sourceElements[$key];
        }
        return $elements;
    }

Usage Example

Beispiel #1
0
 /**
  * Sorts items in this collection.
  * e.g:.
  *
  * ```
  * $itemCollection = new ItemCollection();
  * // warm-up...
  * $items = $itemCollection->sortItems('date', true)->all();
  * ```
  *
  * @param string   $attribute   The name of the attribute used to sort
  * @param bool     $descending  Is descending sort?
  * @param string[] $collections Only the items belong to Collections will be affected
  *
  * @return Yosymfony\Spress\Core\Support\ItemCollection An intance of itself
  */
 public function sortItems($attribute, $descending = true, array $collections = [])
 {
     $itemCollections = $this->all($collections, true);
     $callback = function ($key, ItemInterface $item) use($attribute) {
         $attributes = $item->getAttributes();
         return isset($attributes[$attribute]) === true ? $attributes[$attribute] : null;
     };
     foreach ($itemCollections as $collection => $items) {
         $arr = new ArrayWrapper($items);
         $itemsSorted = $arr->sortBy($callback, null, SORT_REGULAR, $descending);
         $this->itemCollections[$collection] = $itemsSorted;
     }
     $this->items = [];
     foreach ($this->itemCollections as $collection => $items) {
         $this->items = array_merge($this->items, $items);
     }
     return $this;
 }
All Usage Examples Of Yosymfony\Spress\Core\Support\ArrayWrapper::sortBy