Skip to content

Instantly share code, notes, and snippets.

@kythin
Created July 10, 2013 23:53
Show Gist options
  • Save kythin/5971304 to your computer and use it in GitHub Desktop.
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
function flip($arr) {
$out = array();
foreach ($arr as $key => $subarr)
{
foreach ($subarr as $subkey => $subvalue)
{
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
Feed it an array of columns like this:
--------------------------------------
Array
(
[fname] => Array
(
[0] => chris
[1] => joe
)
[email] => Array
(
[0] => chris@email.com
[1] => joe@email.com
)
)
Returns an array of rows with indexed fields like this:
-------------------------------------------------------
Array
(
[0] => Array
(
[fname] => chris
[email] => chris@email.com
)
[1] => Array
(
[fname] => joe
[email] => joe@email.com
)
)
@AkramiPro
Copy link

nice , thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment