summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNathan Gass2010-11-11 16:25:45 +0000
committerNathan Gass2010-11-11 16:25:45 +0000
commitc9dabbd271afb8ac85009cd220f22a20a4373490 (patch)
treeef56e0c3619ec06e11b0219edbb6e135db76b708
parent8874dd2a9b617c7f846fdbaf208e0c611f9aa23a (diff)
downloaditools-c9dabbd271afb8ac85009cd220f22a20a4373490.tar.gz
itools-c9dabbd271afb8ac85009cd220f22a20a4373490.tar.bz2
itools-c9dabbd271afb8ac85009cd220f22a20a4373490.zip
add reorder argument and tests to it::filter_keys
-rw-r--r--it.class22
-rwxr-xr-xtests/it.t17
2 files changed, 33 insertions, 6 deletions
diff --git a/it.class b/it.class
index f8c8553..f3dd0a8 100644
--- a/it.class
+++ b/it.class
@@ -417,15 +417,25 @@ static function replace($replacements, $string, $p = array())
* Extract key => value pairs from assoc array by key
* @param $array array to filter
* @param $keys array or comma separated list of keys to keep
+ * @param $p['reorder'] reorder pairs to the order of the $keys array
*/
-static function filter_keys($array, $keys)
+static function filter_keys($array, $keys, $p = array())
{
$result = array();
- $keep = array_flip(is_string($keys) ? explode(",", $keys) : (array)$keys);
-
- foreach ($array as $key => $val)
- if (isset($keep[$key]))
- $result[$key] = $val;
+ if (is_string($keys))
+ $keys = explode(",", $keys);
+ if ($p['reorder'])
+ {
+ foreach ((array)$keys as $key)
+ $result[$key] = $array[$key];
+ }
+ else
+ {
+ $keep = array_flip((array)$keys);
+ foreach ($array as $key => $val)
+ if (isset($keep[$key]))
+ $result[$key] = $val;
+ }
return $result;
}
diff --git a/tests/it.t b/tests/it.t
index 475ff25..0fa84f2 100755
--- a/tests/it.t
+++ b/tests/it.t
@@ -199,4 +199,21 @@ is(
array( array( 'word1', 'wörd2', 'word_3' ), array( '12', '3', '4' ) ),
"test all=>1,pattern_order=>1"
);
+
+
+# it::filter_keys tests
+
+$data = array('a' => 1, 'b' => 2, 'c' => 3);
+is(it::filter_keys($data, 'a'), array('a' => 1), "select one key");
+is(it::filter_keys($data, array('a', 'b')), array('a' => 1, 'b' => 2), "select two keys with array");
+is(it::filter_keys($data, 'a,b'), array('a' => 1, 'b' => 2), "select two keys with string");
+is(
+ array_keys(it::filter_keys($data, 'b,a')),
+ array('a', 'b'),
+ "keep order of data array per default");
+is(
+ array_keys(it::filter_keys($data, 'b,a', array('reorder' => true))),
+ array('b', 'a'),
+ "reorder with given key order");
+
?>