php PHP中的排序对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/124266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:32:47  来源:igfitidea点击:

Sort Object in PHP

phparrayssorting

提问by jW.

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

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

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

Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.

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

回答by Kent Fredric

Almost verbatim from the manual:

手册中几乎逐字逐句:

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

usort($unsortedObjectArray, 'compare_weights');

If you want objects to be able to sort themselves, see example 3 here: http://php.net/usort

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

回答by Will Shaver

For php >= 5.3

对于 php >= 5.3

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

Note that this uses Anonymous functions / closures. Might find reviewing the php docs on that useful.

请注意,这使用匿名函数/闭包。可能会发现查看 php 文档很有用。

回答by Peter Bailey

You can even build the sorting behavior into the class you're sorting, if you want that level of control

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

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 );

回答by Tom

For that compare function, you can just do:

对于那个比较功能,你可以这样做:

function cmp( $a, $b )
{ 
    return $b->weight - $a->weight;
} 

回答by Adam Wright

The usort function (http://uk.php.net/manual/en/function.usort.php) is your friend. Something like...

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");

Note that any array keys will be lost.

请注意,任何数组键都将丢失。

回答by Jeremy Ruten

You could use the usort()function and make your own comparison function.

您可以使用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;
    }
}

回答by biswarupadhikari

function PHPArrayObjectSorter($array,$sortBy,$direction='asc')
{
    $sortedArray=array();
    $tmpArray=array();
    foreach($this->$array as $obj)
    {
        $tmpArray[]=$obj->$sortBy;
    }
    if($direction=='asc'){
        asort($tmpArray);
    }else{
        arsort($tmpArray);
    }

    foreach($tmpArray as $k=>$tmp){
        $sortedArray[]=$array[$k];
    }

    return $sortedArray;

}

e.g =>

例如 =>

$myAscSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'asc');

$myDescSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'desc');

回答by Ihor Burlachenko

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

您可以拥有与您使用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'));

回答by Wilco

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.

根据您尝试解决的问题,您可能还会发现 SPL 接口很有用。例如,实现 ArrayAccess 接口将允许您像访问数组一样访问您的类。此外,实现 SeekableIterator 接口可以让您像数组一样循环遍历对象。通过这种方式,您可以对对象进行排序,就像它是一个简单的数组一样,可以完全控制它为给定键返回的值。

For more details:

更多细节:

回答by Internet Friend

If you want to explore the full (terrifying) extent of lambda style functions in PHP, see: http://docs.php.net/manual/en/function.create-function.php

如果您想探索 PHP 中 lambda 风格函数的全部(可怕)范围,请参阅:http: //docs.php.net/manual/en/function.create-function.php