Kirby
Kirby

Reputation: 455

How to output a table with rowspan from a MySQL query with PHP

I have a problem formatting a table. I got, from a query, a set of rows similar to this one:

5   23   d
5   23   d
5   23   t
5   24   d
5   24   t
4   23   d
4   23   t

Now, I want to display them in a table, but grouping similar data, something like this:

         d
5   23   d
         t
    24   d
         t
4   23   d
         t

So the <td> for 5 would be <td rowspan='5'> or the one for the first 23 would be <td rowspan='3'>. How can I achieve this?

I thought about making a multidimensional array storing a number for each rowspan, but the original set of rows is longer, so I got lost somewhere, and I guess there's a much easier solution.

Upvotes: 4

Views: 1536

Answers (1)

Muatik
Muatik

Reputation: 4171

You can group the query result by column values. For example:

$grouped=array();
foreach($rows as $r)
  $grouped[ $r[0] ][ $r[1] ][]=$r[2];

Upvotes: 4

Related Questions