diff options
Diffstat (limited to 'it.class')
-rw-r--r-- | it.class | 37 |
1 files changed, 30 insertions, 7 deletions
@@ -961,13 +961,8 @@ static function date($format = "", $stamp = null) return date($formatstring, $stamp); } -/** - * Iterate over an array, replacing every element by function value or expression - * @param $code The function or expression to apply. Expression may contain $k for keys and $v for values - * @param $array The array to iterate over - * @param $p['keys'] Only modify elements with given keys (keys can be array or comma separated) - */ -static function map($code, $array, $p = null) +# Internal: Convert expression or funcname or function literal to callable +static function createfunc($code) { if (is_string($code) && it::match('^[\w:]+$', $code) && is_callable($code)) $code .= '($v)'; @@ -975,6 +970,18 @@ static function map($code, $array, $p = null) if (!is_callable($func = $code) && !function_exists($func = "_it_map_" . md5($code))) eval("function $func(\$k, \$v) { return $code; }"); # Anonymous functions/closures are slower than this (PHP 7.1) + return $func; +} + +/** + * Iterate over an array, replacing every element by function value or expression + * @param $code The function (gets key and value as args) or expression as string (gets $k and $v) to apply + * @param $array The array to iterate over + * @param $p['keys'] Only modify elements with given keys (keys can be array or comma separated) + */ +static function map($code, $array, $p = null) +{ + $func = self::createfunc($code); $result = is_array($array) ? $array : iterator_to_array($array); foreach (isset($p['keys']) ? it::filter_keys($array, $p['keys']) : $array as $k => $v) $result[$k] = $func($k, $v); @@ -983,6 +990,22 @@ static function map($code, $array, $p = null) } /** + * Return only elements of $rray for which $code argument evaluates to true. Preserves keys + * @param $code The function (gets key and value as args) or string expression (gets $k and $v) to evaluate + */ +static function filter($code, $array) +{ + $func = self::createfunc($code); + foreach (is_array($array) ? $array : iterator_to_array($array) as $k => $v) + if ($func($k, $v)) + $result[$k] = $v; + + return (array)$result; +} + + + +/** * Send a mail. * @param $p Header => Content (e.g To => me@example.com, Body => bodytext, Html => htmlbodytext) * @param $p['forcemail'] Send this mail even if we're on a twin or devel machine |