PHP: swapping round columns & rows in field/record data
July 20th, 2010
I'm blogging this just because I couldn't find a solution via Google so I had to figure this out myself and it might save you some time if you're trying to do the same thing.
I have some PHP script that grabs some data out of a MySQL table. However, rather than display it in the normal way:
| resultField1 | resultField2 | resultField3 | resultField4 | resultField5 |
| 2010-12-24 | 55 | red | 1 | Miles Davis |
| 2011-03-30 | 65 | yellow | 0 | Kevin Coyne |
| 2011-06-16 | 82 | purple | 1 | Kate Bush |
I want to swap round the rows and columns so that I display it like this:
| resultField1 | 2010-12-24 | 2011-03-30 | 2011-06-16 |
| resultField2 | 55 | 65 | 82 |
| resultField3 | red | yellow | purple |
| resultField4 | 1 | 0 | 1 |
| resultField5 | Miles Davis | Kevin Coyne | Kate Bush |
The thing to be aware of is that when you use mysql_fetch_assoc to get stuff out of a database, for example:
while($resultArray = mysql_fetch_assoc($selectQuery)) {
Do stuff here ...
}
what you get back is an associative array (that's a hash for folks like me who learnt this stuff in Perl before arriving at PHP). So in the above example $resultArray is an associative array - that is, a set of key/value pairs where the key is the field name and the value is the value in that field for that record. Each iteration through the while loop you get a different record.
So, in effect, it's like an array of associative arrays.
However, what you want in order to be able to swap round fields and columns is an associative array of arrays - that is, a set of key/value pairs where each key is a field name and each value is an array of the values for that field in each record in the data set. So what you need to do is:
- Iterate through each record in the data set (i.e. each row in your results) .
- For each field in the record, assign the field value to an array, a reference to which is the value of the key/value pair in the outer associative array.
If it sounds complicated, then I'm glad I'm not the only one. Actually, it's probably easier to understand by looking at the code:
assocArrayOfArrays-example-PrettyPrinting.html - This is a syntax-highlighted representation of the PHP.
assocArrayOfArrays-example.php.txt - This is the actual PHP saved as a .txt file so that you can see and download it.
And here's the PHP in action:
assocArrayOfArrays-example.php
Potentially similar posts
- Perl basics for beginners (on Windows) – August 2010
- How I record demo videos – March 2009
- How can I deliver server-based help? – February 2009
- Migrating a hosted WordPress site to your local PC – October 2008
- Bob Dylan – more new old stuff – October 2008