Skip to content

Commit

Permalink
Merge pull request #7 from zivkovicp/add-transpose
Browse files Browse the repository at this point in the history
Add transpose method
  • Loading branch information
ajant committed Feb 23, 2018
2 parents 1f1e59b + 9de1296 commit 374877c
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,4 +287,12 @@ exists
SimpleArrayLibrary::setColumn(array(array('foo' => 2), array()), 'foo', 1); // array(array('foo' => 1), array('foo' => 1))
SimpleArrayLibrary::setColumn(array(array('foo' => 2), array()), 'foo', 1, false, false); // array(array('foo' => 2), array())
SimpleArrayLibrary::setColumn(array(array('foo' => 2), array()), 'foo', 1, true, false); // array(array('foo' => 2), array('foo' => 1))
```
transpose
------------------------------
Transpose a matrix

Turns rows into columns, and columns into rows. This is very handy when you need to reshape a dataset for a report or plot.
```php
SimpleArrayLibrary::transpose(array(array(1, 2, 3). array(4, 5, 6))); // array(array(1, 4), array(2, 5), array(3, 6))
```
13 changes: 13 additions & 0 deletions src/Categories/Changers.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,17 @@ public static function setColumn(array $matrix, $column, $value, $insertIfMissin

return $matrix;
}

/**
* @param array $matrix
*
* @return array
*/
public static function transpose(array $matrix)
{
// example #4 explains how this works
// http://php.net/manual/en/function.array-map.php
array_unshift($matrix, null);
return call_user_func_array('array_map', $matrix);
}
}
41 changes: 41 additions & 0 deletions test/SimpleArrayLibrary/TransposeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

use SimpleArrayLibrary\SimpleArrayLibrary;

class TransposeTest extends PHPUnit_Framework_TestCase
{
/**
* @param array $data
*
* @return void
* @dataProvider getData
*/
public function test_function(array $data)
{
// invoke logic & test
$this->assertEquals($data['expResult'], SimpleArrayLibrary::transpose($data['matrix']));
}

/**
* @return array
*/
public function getData()
{
return array(
// #0 column required & present
array(
array(
'matrix' => array(
array(1, 2, 3),
array(4, 5, 6)
),
'expResult' => array(
array(1, 4),
array(2, 5),
array(3, 6)
)
)
)
);
}
}

0 comments on commit 374877c

Please sign in to comment.