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 |
/** * 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; }
protected function sortItemsByAttribute(array $items, $attribute, $sortType) { $arr = new ArrayWrapper($items); $callback = function ($key, ItemInterface $item) use($attribute) { $attributes = $item->getAttributes(); return isset($attributes[$attribute]) === true ? $attributes[$attribute] : null; }; return $arr->sortBy($callback, null, SORT_REGULAR, $sortType === 'descending'); }
public function testSortByKey() { $a = new ArrayWrapper(['level1' => ['a' => ['date' => '2015-11-01', 'id' => 3], 'b' => ['date' => '2015-11-02', 'id' => 2], 'c' => ['date' => '2015-11-03', 'id' => 1]]]); $b = $a->sortBy(function ($key, $value) { return $value['id']; }, 'level1'); $this->assertCount(3, $b); $this->assertEquals(1, array_values($b)[0]['id']); $this->assertEquals(2, array_values($b)[1]['id']); $this->assertEquals(3, array_values($b)[2]['id']); }