Ever had data in the form of rows and columns, where you wanted it as columns and rows? Sometimes you have all the data you need, but it is in the wrong format.

Lets look at the following;

Original table

In the original table the products are in rows. Their imagined sales per year are in columns.

Lets look at how this could be structured programatically. We could represent this in PHP as follows;

If we wanted to display the data as rows of dates and columns of products, we could ‘transpose’ this data. Transposition means to switch rows with columns.

Lets take a look at some code;

In the transposeData function, we take the parameter data and loop over the data, assigning the key to $row and the value of the nested array to $columns.

In the first iteration of this loop, $row would contain the index ( 0 ) and the $columns variable would contain the array ( ‘Products’, ‘2012’, … ).

The nested foreach, loops over the $columns array, assigning the index to $row2 (‘Products’ would be 0 in this case) and the value to $column2 (i.e. ‘Products’).

The actual switch over happens on the assignment of these values to the $retData array.

On the first iteration of the nested loop, $retData would become

array(array(‘Products’)).

On the second nested loop iteration it would become array(array(‘Products’), array(‘2012’)) and so on.

When the outer loop has completed its first iteration, $retData would look like this

array(array(‘Products’), array(‘2012’), array(‘2013’), array(‘2014’), array(‘2015’))

On completing the second iteration of the outer loop, $retData would be;

array(array(‘Products’, ‘Product A’), array(‘2012’, ‘200’), array(‘2013’, ‘100’), array(‘2014’, ‘150’), array(‘2015’, ‘50’))

As we can see, the table is being rebuilt into $retData, column by column, until we end up with a result such as the following table

Final table

Transposition is a mathematical operation performed on matrices. While we did not use any algorithm to transform our data, we did see a neat and simple way to essentially rotate data which we could use when we need to display data in a different manner. Because of the nested foreach, this would be a fairly inefficient way to transform a very large dataset — be warned!