Well, if you're sorting the rows in Javascript, and not in PHP, then PHP doesn't really need to care about what the headings are. All PHP needs to do is output two arrays: one with headings and one with the data. Javascript then takes care of sorting and rendering the table. This would really only work well if you were not doing any pagination or searching and had a fairly small results set.
If you're doing any searching or pagination, however, you'd probably want PHP to take care of all rendering...which can still be done generically, and PHP still doesn't really need to know what the headings are.
For instance, if your query was something like this:
SELECT * FROM table ORDER BY ${REQUEST['orderfield']} ${REQUEST['orderdirection']};
Then you could use the following pseudocode to construct your table:
To generate the header:
$header = "<tr>";
for (i = 0 to number of fields)
{
if (field(i) = $REQUEST['orderfield'])
$header .= "<td>[SORT INDICATOR] fieldname</td>"
else
$header .= "<td>fieldname</td>"
}
To generate the body, once again:
for (i = 0 to number of rows)
{
for (j = 0 to number of fields)
{
//construct table row based on your values of the current row/column pair
}
}
This is far more scalable, as if you ever wanted to use pagination or searching, you no longer need to pull the entire dataset into the javascript page...you simply end up with a different data set and you only transmit to the user the data that fits in the dataset. Also, you never have to change your rendering...that stays the same no matter what the results of your query are.
Now, if you're using AJAX, that's completely different...but something tells me that you're probably not.
Also, it doesn't make sense to put each row of results into an object. That implies that you're going to use PHP to sort the results. When dealing with a database, you should always manipulate your data as much as possible in the context of the database, because it will always be faster than in code.
Consider this: you have a dataset with 10000 records, of which you want the first 10, and you want them sorted by balance due. Are you really going to load all 1000 records and sort them manually in code, whether that be PHP or javascript or whatever? No, you're going to let the RDBMS take care of that, because that's what it's for.