Sort Object in PHP

后端 未结 10 1364
被撕碎了的回忆
被撕碎了的回忆 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:36

    Depending on the problem you are trying to solve, you may also find the SPL interfaces useful. For example, implementing the ArrayAccess interface would allow you to access your class like an array. Also, implementing the SeekableIterator interface would let you loop through your object just like an array. This way you could sort your object just as if it were a simple array, having full control over the values it returns for a given key.

    For more details:

    • Zend Article
    • PHPriot Article
    • PHP Manual
    0 讨论(0)
  • 2020-11-29 02:38

    For that compare function, you can just do:

    function cmp( $a, $b )
    { 
        return $b->weight - $a->weight;
    } 
    
    0 讨论(0)
  • 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'));
    
    0 讨论(0)
  • The usort function (http://uk.php.net/manual/en/function.usort.php) is your friend. Something like...

    function objectWeightSort($lhs, $rhs)
    {
       if ($lhs->weight == $rhs->weight)
         return 0;
    
       if ($lhs->weight > $rhs->weight)
         return 1;
    
       return -1;
    }
    
    usort($unsortedObjectArray, "objectWeightSort");
    

    Note that any array keys will be lost.

    0 讨论(0)
提交回复
热议问题