fork(1) download
  1. <?php
  2. /**
  3.  * @link http://stackoverflow.com/q/9445369/367456
  4.  */
  5.  
  6. $array = range('A', 'M');
  7. $columns = 4;
  8. $length = count($array);
  9.  
  10. print_matrix($array, $columns);
  11.  
  12. $floor = floor($length/$columns);
  13. $modulo = $length % $columns;
  14. $max = $length-1;
  15. $virtual = 0;
  16. $keys = array_keys($array);
  17. $build = array();
  18. foreach($keys as $index => $key)
  19. {
  20. $vkey = $keys[$virtual];
  21. $build[$vkey] = $array[$vkey];
  22. $virtual += $floor + ($index % $columns < $modulo);
  23. ($virtual>$max) && $virtual %= $max;
  24. }
  25.  
  26. print_matrix($build, $columns);
  27.  
  28. function print_matrix($matrix, $columns)
  29. {
  30. echo "One row - " . implode(' ', $matrix) . "\n";
  31.  
  32. foreach(array_chunk($matrix, $columns, 1) as $row)
  33. {
  34. foreach($row as $key => $col)
  35. printf('%s[%2d] ', $col, $key);
  36. echo "\n";
  37. }
  38. echo "\n";
  39. }
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
One row - A B C D E F G H I J K L M
A[ 0] B[ 1] C[ 2] D[ 3] 
E[ 4] F[ 5] G[ 6] H[ 7] 
I[ 8] J[ 9] K[10] L[11] 
M[12] 

One row - A E H K B F I L C G J M D
A[ 0] E[ 4] H[ 7] K[10] 
B[ 1] F[ 5] I[ 8] L[11] 
C[ 2] G[ 6] J[ 9] M[12] 
D[ 3]