Sort ViewHelper <f:sort>
The SortViewHelper sorts the items of an array in ascending or descending order. Items with equal values keep their original order.
Items are sorted in human order: numbers and numeric strings are compared
by their value, so 11 comes before 100. Other strings are compared
in natural, case-insensitive order, so 'img2. comes before
'img10., like PHP's
strnatcasecmp function. All other
values, for example dates, are compared with PHP's comparison rules.
If a property is given, the items are sorted by the value of that
property instead. The items can then be arrays or objects. Properties
are accessed the same way as variables in templates, so getter methods
and nested property paths like author. are supported.
Iterators like generators can yield the same key more than once. All of
their items are used, unless preserve is set: then only the last
item per key is used, like with PHP's
iterator_ function.
Examples
Sort an array
Given numbers = :
<f:sort value="{numbers}" />
[9, 11, 100]
Sort strings in human order
Given files = :
<f:sort value="{files}" />
['img1.png', 'img2.png', 'IMG10.png', 'img12.png']
Sort in descending order
<f:sort value="{numbers}" descending="true" />
[100, 11, 9]
Sort by a property
Given products = :
<f:for each="{products -> f:sort(property: 'price')}" as="product">
{product.title}
</f:for>
Pen Book
Go to the source code of this ViewHelper: SortViewHelper.php (GitHub).
Arguments
The following arguments are available for the sort ViewHelper:
descending
-
- Type
- boolean
- Default
- false
If true, the items are sorted in descending order
preserveKeys
-
- Type
- boolean
- Default
- false
If true, the keys of the original array are preserved. Otherwise the result is reindexed numerically.
property
-
- Type
- string
Name or path of the property to sort by, e.g. "title" or "author.name". If omitted, the items themselves are compared.
value
-
- Type
- array
The array to sort