简体   繁体   English

基于类别的循环结果但仅显示类别一次

[英]Loop results based on category but only show category once

I have a table that has 2 columns:我有一个有 2 列的表:

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:我想循环 Title 的所有结果,但每个分组只显示一次 Product:

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.我正在做一个常规的 do while 循环,当然它显示了每一行的 Product 列。 I know I've done this before but can't for the life of me remember!我知道我以前做过这件事,但我一辈子都记不起来了! Any ideas?有什么想法吗? Thanks.谢谢。

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
        // Then store it in $currentProduct for the next iteration 
        $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.如果您想改用现有的do while -loop,也是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM