Last active
November 6, 2015 22:43
-
-
Save HonzaMac/e310f5b960a74a418dda to your computer and use it in GitHub Desktop.
php transpose data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // dummy implementation by someone on internet | |
| // https://medium.com/@shaun_morrow/transposition-in-php-ef49dde5ca15 | |
| function transposeData($data) | |
| { | |
| $retData = array(); | |
| foreach ($data as $row => $columns) { | |
| foreach ($columns as $row2 => $column2) { | |
| $retData[$row2][$row] = $column2; | |
| } | |
| } | |
| return $retData; | |
| } | |
| // smarter way | |
| function myTransposeData($data){ | |
| return array_map(function (...$lines){ | |
| return $lines; | |
| }, ...$data); | |
| }; | |
| $data = array( | |
| array('Products', '2012','2013','2014','2015'), | |
| array('Product A', '200', '100', '150', '50'), | |
| array('Product B', '50', '80', '120', '160'), | |
| array('Product C', '0', '50', '200', '180') | |
| ); | |
| $data1 = transposeData($data); | |
| $data2 = myTransposeData($data); | |
| var_dump($data2); | |
| var_dump($data1 == $data2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment