用PHP排序对象

时间:2020-03-06 14:37:53  来源:igfitidea点击:

用PHP对对象进行排序的一种优雅方法是什么?我很乐意完成与此类似的事情。

$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);

基本上指定要排序的数组以及要排序的字段。我研究了多维数组排序,那里可能有一些有用的东西,但是我看不到任何优雅或者明显的东西。

解决方案

手册几乎逐字记录:

function compare_weights($a, $b) { 
    if($a->weight == $b->weight) {
        return 0;
    } 
    return ($a->weight < $b->weight) ? -1 : 1;
} 

usort($unsortedObjectArray, 'compare_weights');

如果希望对象能够自行排序,请参见此处的示例3:http://php.net/usort

usort函数(http://uk.php.net/manual/en/function.usort.php)是朋友。就像是...

function objectWeightSort($lhs, $rhs)
{
   if ($lhs->weight == $rhs->weight)
     return 0;

   if ($lhs->weight > $rhs->weight)
     return 1;

   return -1;
}

usort($unsortedObjectArray, "objectWeightSort");

请注意,所有阵列键都将丢失。

我们可以使用usort()函数并创建自己的比较函数。

$sortedObjectArray = usort($unsortedObjectArray, 'sort_by_weight');

function sort_by_weight($a, $b) {
    if ($a->weight == $b->weight) {
        return 0;
    } else if ($a->weight < $b->weight) {
        return -1;
    } else {
        return 1;
    }
}

如果要在PHP中探索lambda样式函数的全部(令人恐惧的)范围,请参阅:
http://docs.php.net/manual/zh/function.create-function.php

如果我们想要那种级别的控制,甚至可以将排序行为构建到要排序的类中

class thingy
{
    public $prop1;
    public $prop2;

    static $sortKey;

    public function __construct( $prop1, $prop2 )
    {
        $this->prop1 = $prop1;
        $this->prop2 = $prop2;
    }

    public static function sorter( $a, $b )
    {
        return strcasecmp( $a->{self::$sortKey}, $b->{self::$sortKey} );
    }

    public static function sortByProp( &$collection, $prop )
    {
        self::$sortKey = $prop;
        usort( $collection, array( __CLASS__, 'sorter' ) );
    }

}

$thingies = array(
        new thingy( 'red', 'blue' )
    ,   new thingy( 'apple', 'orange' )
    ,   new thingy( 'black', 'white' )
    ,   new thingy( 'democrat', 'republican' )
);

print_r( $thingies );

thingy::sortByProp( $thingies, 'prop1' );

print_r( $thingies );

thingy::sortByProp( $thingies, 'prop2' );

print_r( $thingies );

根据我们要解决的问题,我们可能还会发现SPL接口很有用。例如,实现ArrayAccess接口将允许我们像访问数组一样访问类。同样,实现SeekableIterator接口将使我们像数组一样遍历对象。这样,我们可以对对象进行排序,就好像它是一个简单的数组一样,可以完全控制它为给定键返回的值。

更多细节:

  • Zend文章
  • PHPriot文章
  • PHP手册

对于php> = 5.3

function osort(&$array, $prop)
{
    usort($array, function($a, $b) use ($prop) {
        return $a->$prop > $b->$prop ? 1 : -1;
    }); 
}

请注意,这使用了匿名函数/闭包。可能会发现复习有关此文档的php文档很有用。