diff options
author | Urban Müller | 2020-05-25 17:59:31 +0200 |
---|---|---|
committer | Urban Müller | 2020-05-25 17:59:31 +0200 |
commit | 8bf25e3d0df107d9e2920740fccf247903cb612e (patch) | |
tree | 27d91d9319d4ed5066231af28596e1f56583a5de | |
parent | 241d2cd913cbda98764161e1c9d23c35156d836d (diff) | |
download | itools-8bf25e3d0df107d9e2920740fccf247903cb612e.tar.gz itools-8bf25e3d0df107d9e2920740fccf247903cb612e.tar.bz2 itools-8bf25e3d0df107d9e2920740fccf247903cb612e.zip |
allow sorting and mapping functions in sort()
-rw-r--r-- | it.class | 18 |
1 files changed, 14 insertions, 4 deletions
@@ -1182,12 +1182,22 @@ static function json_decode($json, $p = []) } /** - * Retuns sorted array. mode string can contain combinations of a for assoc, k for key, r for reverse and n for numeric + * Retuns sorted array. + * @param $mode contains combinations of a for assoc, k for key, r for reverse and n for numeric + * @param $compare two arg compare function or single arg map function. $mode can k a "" or omitted */ -static function sort($array, $mode = "") +static function sort($array, $mode = "", $compare = null) { - $func = it::replace(array('n' => ""), count_chars($mode, 3)) . "sort"; # count_chars sorts flags - $func($array, it::match('n', $mode) ? SORT_NUMERIC : 0); + if (is_callable($mode) && !(is_string($mode) && strlen($mode) < 3)) # "a" is a func and a mode + list($mode, $compare) = [ "", $mode ]; + + if (!($arg = $compare)) + $arg = it::match('n', $mode) ? SORT_NUMERIC : 0; + else if (($prefix = "u") && (new ReflectionFunction($compare))->getNumberOfRequiredParameters() == 1) + $arg = function($a, $b) use ($compare) { return $compare($a) <=> $compare($b); }; + + $func = $prefix . it::replace(array('n' => ""), count_chars($mode, 3)) . "sort"; # count_chars sorts flags + $func($array, $arg); return $array; } |