[ACCEPTED]-Sort Object in PHP-sorting
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 2 want objects to be able to sort themselves, see 1 example 3 here: http://php.net/usort
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 2 functions / closures. Might find reviewing 1 the php docs on that useful.
You can even build the sorting behavior 2 into the class you're sorting, if you want 1 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 );
For that compare function, you can just 1 do:
function cmp( $a, $b )
{
return $b->weight - $a->weight;
}
The usort function (http://uk.php.net/manual/en/function.usort.php) is your friend. Something 2 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 1 lost.
You could use the usort() function and make your 1 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;
}
}
Update from 2022 - sort array of objects:
usort($array, fn(object $a, object $b): int => $a->weight <=> $b->weight);
Full 1 example:
$array = [
(object) ['weight' => 5],
(object) ['weight' => 10],
(object) ['weight' => 1],
];
usort($array, fn(object $a, object $b): int => $a->weight <=> $b->weight);
// Now, $array is sorted by objects' weight.
// display example :
echo json_encode($array);
Output:
[{"weight":1},{"weight":5},{"weight":10}]
Documentation links:
- usort
- spaceship operator (PHP 7.0)
- scalar type declaration (PHP 7.0)
- return type declaration (PHP 7.0)
- arrow function (PHP 7.4)
Depending on the problem you are trying 10 to solve, you may also find the SPL interfaces 9 useful. For example, implementing the ArrayAccess 8 interface would allow you to access your 7 class like an array. Also, implementing 6 the SeekableIterator interface would let 5 you loop through your object just like an 4 array. This way you could sort your object 3 just as if it were a simple array, having 2 full control over the values it returns 1 for a given key.
For more details:
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');
0
You can have almost the same code as you 1 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'));
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.