Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Object in PHP

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

$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.

like image 218
jW. Avatar asked Sep 23 '08 22:09

jW.


People also ask

How do you sort an object in PHP?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

How do you sort object?

To sort objects, send them down the pipeline to Sort-Object . If you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection. Because one object cannot be sorted, Sort-Object returns the entire collection unchanged.

What is sort function PHP?

Definition and Usage. The sort() function sorts an indexed array in ascending order. Tip: Use the rsort() function to sort an indexed array in descending order.

Can we sort array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


6 Answers

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

like image 97
Kent Fredric Avatar answered Sep 22 '22 19:09

Kent Fredric


For 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.

like image 41
Will Shaver Avatar answered Sep 22 '22 19:09

Will Shaver


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 );
like image 20
Peter Bailey Avatar answered Sep 21 '22 19:09

Peter Bailey


For that compare function, you can just do:

function cmp( $a, $b )
{ 
    return $b->weight - $a->weight;
} 
like image 25
Tom Avatar answered Sep 20 '22 19:09

Tom


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.

like image 35
Adam Wright Avatar answered Sep 21 '22 19:09

Adam Wright


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

$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;
    }
}
like image 36
Paige Ruten Avatar answered Sep 20 '22 19:09

Paige Ruten