What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.
$sortedObjectArary = sort($unsortedObjectArray, $Object-
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:
For that compare function, you can just do:
function cmp( $a, $b )
{
return $b->weight - $a->weight;
}
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'));
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.