How can I sort this array of objects by one of its fields, like name
or count
?
Array
(
[0] => stdClass Object
(
If you need to sort by only one field, then usort
is a good choice. However, the solution quickly becomes messy if you need to sort by multiple fields. In this case, YaLinqo library* can be used, which implements SQL-like query syntax for arrays and objects. It has a pretty syntax for all cases:
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Here, '$v->count'
is a shorthand for function ($v) { return $v->count; }
(either can be used). These method chains return iterators, but you can get arrays by adding ->toArray()
in the end if you need it.
* developed by me