Created
July 10, 2013 23:53
-
-
Save kythin/5971304 to your computer and use it in GitHub Desktop.
Beautifully simple columns to rows array flip in PHP. I didn't write this one, I've done this a hundred times for quick and dirty CSV processing scripts, but never kept nice clean code like this. Taken from http://stackoverflow.com/questions/2221476/php-how-to-flip-the-rows-and-columns-of-a-2d-array
This file contains 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
function flip($arr) { | |
$out = array(); | |
foreach ($arr as $key => $subarr) | |
{ | |
foreach ($subarr as $subkey => $subvalue) | |
{ | |
$out[$subkey][$key] = $subvalue; | |
} | |
} | |
return $out; | |
} |
This file contains 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
Feed it an array of columns like this: | |
-------------------------------------- | |
Array | |
( | |
[fname] => Array | |
( | |
[0] => chris | |
[1] => joe | |
) | |
[email] => Array | |
( | |
[0] => [email protected] | |
[1] => [email protected] | |
) | |
) | |
Returns an array of rows with indexed fields like this: | |
------------------------------------------------------- | |
Array | |
( | |
[0] => Array | |
( | |
[fname] => chris | |
[email] => [email protected] | |
) | |
[1] => Array | |
( | |
[fname] => joe | |
[email] => [email protected] | |
) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice , thank you