Sort array of objects by object fields

后端 未结 19 1875
情书的邮戳
情书的邮戳 2020-11-22 02:28

How can I sort this array of objects by one of its fields, like name or count ?

  Array
(
    [0] => stdClass Object
        (
          


        
19条回答
  •  独厮守ぢ
    2020-11-22 03:17

    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

提交回复
热议问题