tags:

views:

69

answers:

2

This is probably really obvious and simple - but it isn't to me with my rudimentary knowledge:)

I've got two tables:

table_items
-----------
item_id ¦ item_name ¦ item_describtion ¦ more item stuff.....

table_subitems
-----------------
subitem_id ¦ item_id ¦ subitem_name ¦ More subitem stuff

Each item can have zero to pretty much unlimited subitems, and are related by the fields item_id.

I want to print out the subitems grouped by item.

I am currently doing this with a query which selects subitems where table_items.item_id = table_subitems.item_id and then displays them with a while loop, which is fine as far as it goes, I get something like this:

Item One
========
Subitem 0ne

Item One
========
Subitem two

Item One
========
Subitem three

Item Two
========
Subitem one

Item Three
==========
Subitem one

Item Three
==========

 Subitem two

But I want

ITEM ONE
--------
Subitem one
Subitem two
Subitem three

ITEM TWO
--------
Subitem one

ITEM THREE
----------
Subitem one
Subitem two

How do I do this? Is it a function of the query or of how I show the results?

My knowledge of PHP is growing but still limited, and I'm doing this in a procedural way (ie it's not OOP, which I am trying to grasp but haven't fully) so talk to me like I'm stupid.

+1  A: 

You could do something like this, printing a new ITEM NAME each time it changes:

$last_item_id = null;

foreach ($rows as $row) {
    if ($row->item_id != $last_item_id) {
        echo "<h2>{$row->item_name}</h2>\n";
        $last_item_id = $row->item_id;
    }

    echo "{$row->subitem_name}<br />\n";
}
John Kugelman
A: 

Use a variable that holds the last heading and print the current heading only if it differs from the last:

$last = null;
while ( /* … */ ) {
    if ($row['item_id'] != $last) {
        echo '<hx>'.$row['item_name'].'</hx>';
        $last = $row['item_id'];
    }
    echo $row['subitem_name'];
}
Gumbo
Thank, worked perfectly!
Katherine