From 05784e75c66f54d47e1ecc1128850cf247c7cdc9 Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Mon, 9 Aug 2021 08:03:51 +0200 Subject: New package --- sort_recursively.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 sort_recursively.php (limited to 'sort_recursively.php') diff --git a/sort_recursively.php b/sort_recursively.php new file mode 100644 index 0000000..4d089e1 --- /dev/null +++ b/sort_recursively.php @@ -0,0 +1,40 @@ + gettype($b); + } else { + return $a <=> $b; + } +} + +/** + * Sort an array by its values, recursively + * @param array &$array + */ +function sortRecursively(array &$array): void +{ + // Sequential array, re-index after sorting + if (array_keys($array) === range(0, count($array) - 1)) { + usort($array, 'byTypeAndValue'); + } + // Associative array, maintain keys + else { + uasort($array, 'byTypeAndValue'); + } + + foreach ($array as &$value) { + if (is_array($value)) { + sortRecursively($value); + } + } +} -- cgit