Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

There is a two-dimensional array describing a HTML table. Each element of the array consists of:

  • the cell content
  • rowspan
  • colspan

Every row of this two dimensional array corresponds to <td> cells of a <tr> of the table which my software should generate.

I need to "reverse" the array (interchange vertical and horizontal direction).

Insofar I considered algorithm based on this idea: make a rectangular matrix of the size of the table and store in every element of this matrix the corresponding index of the element of the above mentioned array. (Note that two elements of the matrix may be identical due rowspan/colspan.) Then I could use this matrix to calculate rowspan/colspan for the inverted table.

But this idea seems bad for me. Any other algorithms?

Note that I program in PHP.

share|improve this question
2  
Your idea seems sound. The operation you're performing is called transposing a matrix. Handling rowspan and colspan might be tricky, though, if you need to reconstruct the array from HTML. –  lserni Nov 6 at 23:00
 
I suppose that if, after you 'reverse' the array, you swap the rowspan and colspan values on every element your table should be properly reversed. –  xpy Nov 24 at 19:20
 
@xpy: sadly it is more complex than this –  porton Nov 24 at 22:45
add comment

1 Answer

// Assumes source array is $input

// find the "longest" subarray
$max = 0;
foreach ($input as $subarray)
  $max = max($max, count($subarray));

// generate a transposed output array
$output = array();
for ($i = 0; $i < $max; ++$i)
  $output[] = array_column($input, $i);

See http://www.php.net/manual/en/function.array-column.php

share|improve this answer
1  
Programmers is about conceptual questions and I expect answers to explain things. Throwing code dumps instead of explanation is like copying code from IDE to whiteboard: it may look familiar and even sometimes be understandable, but it feels weird... just weird. Whiteboard doesn't have compiler –  gnat Nov 22 at 17:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.