Reputation: 2172
I have an object that is somewhat like this:
<?php
class Change {
private $prop1, $prop2, $prop3;
public function __construct($prop1, $prop2, $prop3) {
$this->$prop1=$prop1;
$this->$prop2=$prop2;
$this->$prop3=$prop3;
}
public function getProp1() {
return $this->prop1;
}
public function getProp2() {
return $this->prop2;
}
public function getProp3() {
return $this->prop3;
}
}
?>
I've removed some of the details, but that is generally what the objects are. Right now, I want to sort objects with prop1
not equal to NULL
at the top then sort by specific values for prop2
. Prop2
can be equal to "High", "Medium", "Low", "Critical", or any other value the user enters. I want to sort them in this order: Critical, High, Medium, Low, everything else. Finally, I want to sort on prop3
alphabetically.
Is this possible in to do with usort? Is there an easier way?
Sort Order:
Prop1
- Not NULL
Prop2
- "Critical", "High", "Medium", "Low", *Prop3
- AlphabeticalUpvotes: 0
Views: 591
Reputation: 121
function sort($a,$b){
$criteria = array('Critical'=>4,'High'=>3,'Medium'=>2,'Low'=>1);
if($a.Prop1 != NULL && $b.Prop1 == NULL) return -1;
if($criteria[$a.Prop2] != $criteria[$b.Prop2]) {
if($criteria[$a.Prop2] < $criteria[$b.Prop2]){
return -1;
}else{
return 1;
}
}
return strcmp($a.Prop3,$b.Prop3);
}
Sorry, I don't test it, but it must work in this way
Upvotes: 1