public
Created

flip orientation

  • Download Gist
flip-orientation.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?php
/**
* @link http://stackoverflow.com/q/9445369/367456
*/
 
$array = range('A', 'M');
$columns = 4;
$length = count($array);
 
print_matrix($array, $columns);
 
$floor = floor($length/$columns);
$modulo = $length % $columns;
$max = $length-1;
$virtual = 0;
$keys = array_keys($array);
$build = array();
foreach($keys as $index => $key)
{
$vkey = $keys[$virtual];
$build[$vkey] = $array[$vkey];
$virtual += $floor + ($index % $columns < $modulo);
($virtual>$max) && $virtual %= $max;
}
 
print_matrix($build, $columns);
 
function print_matrix($matrix, $columns)
{
echo "One row - " . implode(' ', $matrix) . "\n";
 
foreach(array_chunk($matrix, $columns, 1) as $row)
{
foreach($row as $key => $col)
printf('%s[%2d] ', $col, $key);
echo "\n";
}
echo "\n";
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.