Php – Reverse horizontal and vertical for a HTML table

algorithmshtmlPHP

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.

Best Answer

The only difficulty is to find on which column a cell starts. Once you figure how to do that you can collect the cells for each column and output them as a row, exchanging colspan and rowspan. To find the starting colum you have to track what part of the table positions is used by previous cells. Each cell starts at the next available position.

I don’t know php, so I will use pseudocode.

The input is an array that gives for each row the list of variable-sized cells. The output is in the same format.

I will assume the table fills a rectangular area. If not, some padding with empty cells will be neessary in the output.

function reverse( table:array of array of cell ) 
{
  used = new array of array of boolean.
  output = new array of array of cell

  for r = 0 to table.size()-1 {
    // process row r
    c = 0;
    for each cell in table[r] {
      // skip to next position
      while used[r][c] { c++; }
      // cell starts at column c.  add it to the output
      cell2 = cell with rowspan and colspan values switched
      output[c].append(cell2)
      // mark used table positions (use 1 for missing rowspan/colspan)
      for i = 0 to cell.rowspan-1 {
        for j = 0 to cell.colspan-1 {
          used[r+i][c+j] = true;
        }
      }
    }
  }

  return output;
}

I hope you can translate it to php.

Related Topic