EDITED: It's harder than I thought, and I messed it up for the first time (or two). Now it should work.
Let's say you have a 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 size of the table. To do this, we can take the count first row, since we know that the first row should be the maximum width of the table. Height is simply 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 it by taking $ width * $ height.
$total = $width * $height;
Then it's really just math to figure out where everything goes. We must use a separate counter for old and new indexes, because we will have to increase them differently as soon as 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]; } }