phppervasive-sql

how to Loop through PDO object and group rows with matching column


I am working on a web report and I need to have it look like the below format. The data is coming from a PDO object that I get in php. but I am not sure how I can print this out so that the product_line isn't repeated because each entry in the PDO project does have a product line. It should print the product line and then print all jobs with that product line before moving on to the next product line. is it possible to loop through my PDO object, print out a product_line, then print every item with matching product_line before moving on to the next product_line?

Part   Job   Seq  Workcenter  Source  Cause    Date     Notes
---------------------------------------------------------
Product_Line
103V   A306  003  Bending    Prep    Wrong   4/1/2022 blah blah blah
102V   B306  002  Laser Op   Laser   error   3/31/2022 some more notes
Product_Line
864A   M037  008  Waterjet   skids  detail wrong 3/31/2022 more notes

Solution

  • make sure your query is ordering by product line, then create a variable to store the current product line. after, start a for loop to print each product, but first check if the product line of the product is different from the one you stored in the variable. if so, print a new header and, store this new product line in the variable.

    $current_product_line = "";
    
    foreach ($products as $product) {
        if ($current_product_line!= $product["product_line"]) {
            // print header
            $current_product_line = $product["product_line"];
        }
        // print your product
    }