From 94216da27605b9e6b15b313bc4d963fc30e0fe43 Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Fri, 17 Jul 2009 00:01:06 +0000 Subject: [PATCH] MINOR Documented and unit tested ArrayLib::invert() (merged from branches/2.3-nzct) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@82068 467b73ca-7a2a-4603-9d3b-597d59a354a9 --- core/ArrayLib.php | 45 +++++++++++++++++++++++++++++++++++++++--- tests/ArrayLibTest.php | 33 +++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 tests/ArrayLibTest.php diff --git a/core/ArrayLib.php b/core/ArrayLib.php index 361b022ff..eb7d4b2ec 100755 --- a/core/ArrayLib.php +++ b/core/ArrayLib.php @@ -5,15 +5,54 @@ * @subpackage misc */ class ArrayLib extends Object { + + /** + * Inverses the first and second level keys of an associative + * array, keying the result by the second level, and combines + * all first level entries within them. + * + * Before: + * + * array( + * 'row1' => array( + * 'col1' =>'val1', + * 'col2' => 'val2' + * ), + * 'row2' => array( + * 'col1' => 'val3', + * 'col2' => 'val4' + * ) + * ) + * + * + * After: + * + * array( + * 'col1' => array( + * 'row1' => 'val1', + * 'row2' => 'val3', + * ), + * 'col2' => array( + * 'row1' => 'val2', + * 'row2' => 'val4', + * ), + * ) + * + * + * @param array $arr + * @return array + */ static function invert($arr) { - if (! $arr) return false; + if(!$arr) return false; + $result = array(); foreach($arr as $columnName => $column) { foreach($column as $rowName => $cell) { - $output[$rowName][$columnName] = $cell; + $result[$rowName][$columnName] = $cell; } } - return $output; + + return $result; } /** diff --git a/tests/ArrayLibTest.php b/tests/ArrayLibTest.php new file mode 100644 index 000000000..4839e4e0e --- /dev/null +++ b/tests/ArrayLibTest.php @@ -0,0 +1,33 @@ + array( + 'col1' =>'val1', + 'col2' => 'val2' + ), + 'row2' => array( + 'col1' => 'val3', + 'col2' => 'val4' + ) + ); + + $this->assertEquals( + ArrayLib::invert($arr), + array( + 'col1' => array( + 'row1' => 'val1', + 'row2' => 'val3', + ), + 'col2' => array( + 'row1' => 'val2', + 'row2' => 'val4', + ), + ) + ); + } +} \ No newline at end of file