Sort array of objects by object fields

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

    You can use sorted function from Nspl:

    use function \nspl\a\sorted;
    use function \nspl\op\propertyGetter;
    use function \nspl\op\methodCaller;
    
    // Sort by property value
    $sortedByCount = sorted($objects, propertyGetter('count'));
    
    // Or sort by result of method call
    $sortedByName = sorted($objects, methodCaller('getName'));
    
    0 讨论(0)
提交回复
热议问题