Skip to content

Instantly share code, notes, and snippets.

@morozov
Created September 22, 2018 01:36
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 morozov/16324e5320c272de59f44a45a93c7b1a to your computer and use it in GitHub Desktop.
Save morozov/16324e5320c272de59f44a45a93c7b1a to your computer and use it in GitHub Desktop.
<?php
class Sorter
{
private $callback;
public function __construct(array $orderBy)
{
$functions = [];
foreach ($orderBy as $field => $order) {
$multiplier = strtolower($order) === 'desc' ? -1 : 1;
$functions[] = function (array $a, array $b) use ($field, $multiplier) : int {
if (! isset($a[$field], $b[$field])) {
return 0;
}
return (
!isset($a[$field]) <=> !isset($b[$field]) ?: $a[$field] <=> $b[$field]
) * $multiplier;
};
}
$this->callback = function (array $a, array $b) use ($functions) : int {
foreach ($functions as $function) {
$result = $function($a, $b);
if ($result !== 0) {
return $result;
}
}
return 0;
};
}
public function __invoke(array $a, array $b) : int
{
return ($this->callback)($a, $b);
}
}
$sorter = new Sorter(['a' => 'asc']);
$data = [
['a' => 'y'],
['a' => 'x'],
];
usort($data, $sorter);
var_dump($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment