Sort array of objects by object fields

后端 未结 19 1578
情书的邮戳
情书的邮戳 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:13

    A simple alternative that allows you to determine dynamically the field on which the sorting is based:

    $order_by = 'name';
    usort($your_data, function ($a, $b) use ($order_by)
    {
        return strcmp($a->{$order_by}, $b->{$order_by});
    });
    

    This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.

提交回复
热议问题