Originally posted by Zimm
I am attempting to split a list of information gathered from a mysql database into two columns using a table. Actually, I'm wondering if it's possible...
The idea is to retrieve rows from a table in a mysql database using mysql, dividing it in half, and listing half of it in one column of a table and the other half in the other column of the table.
So: data a, data b, data c would be:
data a data c
data b
Is it possible to do this? If so, how?
Of course it's possible! In the right hands, computers can be very powerful devices, you know 🆒
There are two methods: one cheap-n-nasty (a two-column table with a nested table containing half the list in each column that leaves you open to all sorts of ugly alignment hassles), the other a bit smarter.
That is to read all the data into an array, eg. while($data[]=mysql_fetch_array($result))
Get count($data) and halve that, rounding up if necessary (use ceil()) to find out where the second column starts. Call it $half. Actually, now I think of it, better use mysql_num_rows($result) instead: count($data) will be off by one, with a bogus 'false' entry on the end put there by the while loop.
$loop from 0 to $half-2, printing side-by-side $data[$loop] and $data[$loop+$half]. The last line printed in the loop will contain $data[$half-2] and $data[$half+$half-2].
That covers everything from $data[0] up to $data[$half-2] and $data[$half] up to $data[$half+$half-2].
For an illustration of all that:
EXAMPLE 1. 11 Entries.
a g
b h
c i
d j
e k
f
mysql_num_rows($data)=11;
$half=ceil(11/2.0)=6;
$loop from 0 to $half-2
$loop ... $data[$loop] ... $data[$loop+$half]
0 ... $data[0]=a ... $data[6]=g
1 ... $data[1]=b ... $data[7]=h
2 ... $data[2]=c ... $data[8]=i
3 ... $data[3]=d ... $data[9]=j
4 ... $data[4]=e ... $data[10]=k
---------------------------------------------
EXAMPLE 2. 10 Entries.
a f
b g
c h
d i
e j
mysql_num_rows($numrows)=10;
$half=ceil(10/2.0)=5;
$loop from 0 to $half-2
$loop ... $data[$loop] ... $data[$loop+$half]
0 ... $data[0]=a ... $data[5]=f
1 ... $data[1]=b ... $data[6]=g
2 ... $data[2]=c ... $data[7]=h
3 ... $data[3]=d ... $data[8]=i
That just leaves the last line, which has to be treated differently, because it might be incomplete (i.e., an odd number of entries).
If there are an even number of entries in the list, the missing two are $data[$half-1] and $data[$half+$half-1]. If there are an odd number, the only one still needing to be printed is $data[$half-1] (and some sort of blank in the right-hand column).