PHP Grouping Results
- Started
- Last post
- 8 Responses
- seed
Can anyone tell me how to group an output to only show the related category name once and display all items in that category? Example:
Category 1
Item 1
Item 2
Item 3Category 2
Item 1
Item 2
Item 3
Item 4In the database, item.cat_id = cat.id
- drgs0
tarzan not understand...
- hyt0
SELECT i.tem, c.category FROM item AS i, cat AS c WHERE i.cat_ID = $categoryID AND c.ID = $categoryID
$categoryID needs to come from somewhere though...
(Also the above is probably somewhat convoluted but I'm tired...)
- maximillion_0
look up "group by" clause on mysql.com
- seed0
I get the idea of 'group by' but Im not sure how to make the result output the Category name once above each grouping. I am looking at the links above also.
- maximillion_0
assuming you link the categories to the items via an id, i would put the category names into an array with the id as key. do yr query and loop through the items detecting when the cat id changes (record the last id used and then detect when its different) then use the id to ref the name in the array you made
- heavyt0
Agree with Maxi.
What I have done in the past is to use a var to hold the current category name. As you loop through your results, check each time if the category == that var. If it does, you are still in the same category. If it is not equal, you know you've moved on to the next cat.
- seed0
That sounds like the way to go. I am weak on arrays. I'll work on that. Thanks.