Skip to content

Instantly share code, notes, and snippets.

@mlebkowski
Created July 21, 2014 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlebkowski/914aa7b6864d03e9eb50 to your computer and use it in GitHub Desktop.
Save mlebkowski/914aa7b6864d03e9eb50 to your computer and use it in GitHub Desktop.
SortableInterface
<?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";
@frydlewicz
Copy link

W linii 17. rozumiem, że się pomyliłeś i miało być ogólnie "id", a nie "disease_id", mam rację?

@frydlewicz
Copy link

w 39. średnik niepotrzebny.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment