Created
June 6, 2023 12:09
-
-
Save ziadoz/4236f7d534ca186767f8b0c825bc438c to your computer and use it in GitHub Desktop.
PHP Sort Associative Array
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 | |
final class SortAssoc | |
{ | |
public function __construct(private readonly array $array, private readonly array $columns = []) | |
{ | |
} | |
public function __invoke(): array | |
{ | |
$array = $this->array; | |
usort($array, function (array $a, array $b) { | |
$left = []; | |
$right = []; | |
foreach ($this->columns as $column) { | |
$left[] = $a[$column] ?? throw new \OutOfBoundsException(sprintf('Invalid filter key: %s', $column)); | |
$right[] = $b[$column] ?? throw new \OutOfBoundsException(sprintf('Invalid filter key: %s', $column)); | |
} | |
return [$left] <=> [$right]; | |
}); | |
return $array; | |
} | |
} | |
$array = [ | |
['name' => 'Joe Bloggs', 'age' => 42], | |
['name' => 'Jane Bloggs', 'age' => 24], | |
]; | |
$sorted = (new SortAssoc($array, ['name', 'age']))->__invoke(); | |
print_r($sorted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment