Sort Object in PHP

后端 未结 10 1406
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 01:51

What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.

$sortedObjectArary = sort($unsortedObjectArray, $Object-         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 02:40

    You can have almost the same code as you posted with sorted function from Nspl:

    use function \nspl\a\sorted;
    use function \nspl\op\propertyGetter;
    use function \nspl\op\methodCaller;
    
    // Sort by property value
    $sortedByWeight = sorted($objects, propertyGetter('weight'));
    
    // Or sort by result of method call
    $sortedByWeight = sorted($objects, methodCaller('getWeight'));
    

提交回复
热议问题