Created
July 21, 2014 08:45
-
-
Save mlebkowski/914aa7b6864d03e9eb50 to your computer and use it in GitHub Desktop.
SortableInterface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface SortableInterface { | |
public function getSortValues(); | |
} | |
class A implements SortableInterface { | |
private $order, $price, $id; | |
public function __construct($price, $id, $order) { | |
$this->id = $id; | |
$this->price = $price; | |
$this->order = $order; | |
} | |
public function getSortValues() { | |
return [ | |
'has_price' => null !== $this->price, | |
'has_disease_id' => null !== $this->id, | |
'order' => - $this->order, | |
]; | |
} | |
public function toString() { | |
return sprintf("%s %s %s", $this->price?:"NULL", $this->id ?: "NULL", $this->order ?: "NULL"); | |
} | |
} | |
function custom_sort(SortableInterface $s1, SortableInterface $s2) | |
{ | |
$values1 = $s1->getSortValues(); | |
$values2 = $s2->getSortValues(); | |
do { | |
$c1 = (int) array_shift($values1); | |
$c2 = (int) array_shift($values2); | |
if ($c1 !== $c2) { | |
return $c2 - $c1; | |
} | |
} while (count($values1) && count($values2)); | |
return 0; | |
}; | |
$collection = [ | |
new A(100, 1, 1), | |
new A(130, null, 1), | |
new A(20, null, 3), | |
new A(null, 1, 5), | |
new A(null, 3, 3), | |
new A(null, 3, 1), | |
new A(null, null, 4), | |
new A(null, null, 1), | |
new A(null, null, null), | |
]; | |
uasort($collection, 'custom_sort'); | |
foreach ($collection as $item) echo $item->toString(), "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
w 39. średnik niepotrzebny.