Question: I am tring to display all my products within their category, so something like:

Category Name1
 Product Name1, Product Name2 ...
Category Name2
 Product Name3, Product Name4 ...

I am using oscommerce, So the database structure is not my choice. The database tables I need to use are

products\_to\_categories: holds the products\_id and categories\_id
products\_description:holds products\_id and products\_name (other info in this table are not important)
category\_description: holds the categories\_id and categories\_name

I have tried everything and i only can get to echo the products (all together) and categories all together, but I can't get them in a way that all the products within a category sit under the specified name

As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products

I really hope you can help

thanks

Answer: 
There are two ways of approaching this, and the idea behind is was already given as an answer here, by Zod.

The first way is using category\_description to get **all** categories (whether it's full of products or not), the second way is to only extract categories that are used (i.e., not getting a complete list of categories). I'll go through the first way; getting all categories.

Run through category\_description, and get the IDs and category names into an Array.

Now, run through that array with `foreach` and grab all product\_ids from products\_to\_categories. (`SELECT products_id FROM products_to_categories WHERE categories_id=[CATEGORY ID GOES HERE]`).

Now that you have your product IDs that are associated with the concurrent category, you can run through the products\_description and get their name. Essentially, your code should look like:

```
foreach ($categories as $category) {
   ...display category name and run code to get product ids...
   foreach ($products as $product) {
       ...get product name from products_description...
       ...display product name...
   }
}

```
I dont understand fully how you want to display. I hope you like to display like this 

```
Category Name1 
        Product Name1
        Product Name2 
Category Name2 
        Product Name3
        Product Name4

```

Easiest way i think, get distinct list of category in an array.
with cat id and cat name
Loop that array and print products for each Category.

If category list is huge storing it in array and looping will be a bad idea.