I'm looking for a way, either via SQL or PHP, to return many columns from an SQL statement but be able to iterate through them one column at a time.
I have a query which gives me for example:
ID | N1 | N2
1 | 15 | 20
2 | 25 | 30
3 | 35 | 40
I know I can go through with a foreach $result as $row
and use $row['T1']
in the loop, but I'm looking for a way to put ALL $row['T1']
into an array without having to iterate over them. I havn't been able to find how to do this.
I would need an array (or set of arrays) which would be organized as:
myArray = array( 'N1' => array('15', '25', '35'),
'N2' => array('20', '30', '40')
);
so that I can access them using standard array functions like array_sum()
and array_slice()
.
Is there a way, using MySQL, PHP(PDO), to do this simply and programmatically for a large number of fields?
My SQL uses a complicated join to get many fields, these fields need to be averaged and printed to a text file. They would like to group the fields together, not have all fields in a standard table.
N1:
15
25
35
N2:
20
30
40
Hence needing the array properly set up.
So: Which method can I use to do this? I know I can iterate over the whole $result
and push the $row['index']
into several of my own arrays, but surely there's a better way to do this? With a complicated join, is it quicker to do a seperate query for each field individually?