在PHP中排序对象

jW.*_*jW. 43 php arrays sorting

在PHP中对对象进行排序的优雅方法是什么?我很想完成类似的事情.

$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);
Run Code Online (Sandbox Code Playgroud)

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

Ken*_*ric 73

几乎逐字逐句:

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

usort($unsortedObjectArray, 'compare_weights');
Run Code Online (Sandbox Code Playgroud)

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


Wil*_*ver 20

对于php> = 5.3

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

请注意,这使用匿名函数/闭包.可能会发现审查有用的PHP文档.

  • 如果 `$a-&gt;$prop == $b-&gt;$prop` 会怎样? (2认同)

Pet*_*ley 5

如果您想要这种级别的控制,您甚至可以将排序行为构建到您正在排序的类中

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 );
Run Code Online (Sandbox Code Playgroud)

  • @Lobo PHP 5在我写这篇文章的时候已经4岁了,现在已经4年了.我想8年后,我们可以安全地将PHP4放到牧场. (18认同)