Created
September 22, 2018 01:36
-
-
Save morozov/16324e5320c272de59f44a45a93c7b1a to your computer and use it in GitHub Desktop.
This file contains 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 | |
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