From 9113cad57ec737bf8cb75bf41f969082e89861fb Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Sun, 26 Sep 2021 01:02:18 +0200 Subject: [PATCH] Add new class MD_STD_SORT to provide useful sorting tools --- src/MD_STD_SORT.php | 72 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/MD_STD_SORT.php diff --git a/src/MD_STD_SORT.php b/src/MD_STD_SORT.php new file mode 100644 index 0000000..9461642 --- /dev/null +++ b/src/MD_STD_SORT.php @@ -0,0 +1,72 @@ + $b[$sortIndex] ? -1 : 1; + }; + + } + + /** + * Provides a function usable by usort that sorts first by string occurence, + * then by an integer value provided in another part of the array. + * + * @param string $nameIndex Index of the name column. + * @param string $searchValue Value to search for. + * @param array $extSortBy External list to sort by, e.g. + * similarities as per levinsthein. + * @param string $sortIndex Index to sort by in case the name + * index didn't return a hit. + * + * + * @return closure + */ + public static function sort_by_string_occurence_and_ext_sort_index(string $nameIndex, string $searchValue, array $extSortBy, string $sortIndex):closure { + + return function (array $a, array $b) use ($nameIndex, $searchValue, $extSortBy, $sortIndex) { + + if ($a == $b) { + return 0; + } + + if ($a[$nameIndex] === $searchValue) return -1; + if ($b[$nameIndex] === $searchValue) return 1; + + if (stripos($a[$nameIndex], $searchValue) !== false) return -1; + if (stripos($b[$nameIndex], $searchValue) !== false) return 1; + + return $extSortBy[$a[$sortIndex]] > $extSortBy[$b[$sortIndex]] ? -1 : 1; + }; + + } +}