Ironank Ironank - 5 months ago 14
SQL Question

Loop results based on category but only show category once

I have a table that has 2 columns:

Product
Title


I'm doing:

SELECT * FROM products ORDER BY product


I want to loop all the results of Title but only show Product once per grouping:

Product
--Title
--Title
--Title

Product
--Title
--Title
--Title


I'm doing a regular do while loop and of course it's showing the Product column for each row. I know I've done this before but can't for the life of me remember! Any ideas? Thanks.

Answer

Since you're already ordering your result by product, you could do something like this:

$currentProduct = null;

foreach($products as $product) {

    if ($currentProduct != $product['product']) {
        // We got a new product. Show it with some fancy html
        $currentProduct = $product['product'];
    }

    // Show the title with some fancy html
}

If you want to use your existing do while-loop instead, it's the same.