Skip to content
Advertisement

Display table values vertically while keeping table structure

Been checking out other ways used to order array values vertically for use in a table but most of them were the equivalent of flipping your table 90 deg to the right. I’ve been trying to think of a way to properly implement this but I think I need some help.

For example, the table (horizontal order):

a  b  c  d  e
f  g  h  i  j
k  l  m  n  o
p  q  r

Is reordered to (vertical order):

a  e  i  m  p
b  f  j  n  q
c  g  k  o  r
d  h  l   

As you can see the structure is retained since the last 2 cells are empty.

Not like this:

a  e  i  m  q
b  f  j  n  r
c  g  k  o
d  h  l  p

In this example, the table is akin to flipping it sideways. Does anyone know how to properly do this?

Advertisement

Answer

EDITED: This is harder than I thought and I messed it up the first time (or two). It should work now.

Let’s say you have your table structure stored in a two dimensional array:

$data = array(
  array('a', 'b', 'c', 'd', 'e'),
  array('f', 'g', 'h', 'i', 'j'),
  array('k', 'l', 'm', 'n', 'o'),
  array('p', 'q', 'r')
);

Since you want to keep the same “shape” you need to determine the dimensions of the table. To do this we can take the count of the first row, since we know that the first row must be the maximum width of the table. The height is just the number of elements in the array.

$width = count($data[0]); // 5
$height = count($data);   // 4

We also need the total number of elements, but we can overestimate by taking $width * $height.

$total = $width * $height; // 20

Then it’s really just a little math to calculate where things go. We have to use a separate counter for the old and new indices because we will have to increment them differently once we start to have holes.

$new_data = array();
$j = 0;
for($i = 0; $i < $total; $i++) {
  $old_x = floor($i / $width); // integer division
  $old_y = $i % $width;        // modulo

  do {
    $new_x = $j % $height;        // modulo
    $new_y = floor($j / $height); // integer division
    $j++;
  // move on to the next position if we have reached an index that isn't available in the old data structure
  } while (!isset($data[$new_x][$new_y]) && $j < $total);

  if (!isset($new_data[$new_x])) {
    $new_data[$new_x] = array();
  }
  if (isset($data[$old_x][$old_y])) {
    $new_data[$new_x][$new_y] = $data[$old_x][$old_y];
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement