mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
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
This commit is contained in:
parent
e6ade3d64b
commit
94216da276
@ -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:
|
||||
* <example>
|
||||
* array(
|
||||
* 'row1' => array(
|
||||
* 'col1' =>'val1',
|
||||
* 'col2' => 'val2'
|
||||
* ),
|
||||
* 'row2' => array(
|
||||
* 'col1' => 'val3',
|
||||
* 'col2' => 'val4'
|
||||
* )
|
||||
* )
|
||||
* </example>
|
||||
*
|
||||
* After:
|
||||
* <example>
|
||||
* array(
|
||||
* 'col1' => array(
|
||||
* 'row1' => 'val1',
|
||||
* 'row2' => 'val3',
|
||||
* ),
|
||||
* 'col2' => array(
|
||||
* 'row1' => 'val2',
|
||||
* 'row2' => 'val4',
|
||||
* ),
|
||||
* )
|
||||
* </example>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
33
tests/ArrayLibTest.php
Normal file
33
tests/ArrayLibTest.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/**
|
||||
* @package sapphire
|
||||
* @subpackage tests
|
||||
*/
|
||||
class ArrayLibTest extends SapphireTest {
|
||||
function testInvert() {
|
||||
$arr = array(
|
||||
'row1' => 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',
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user