Peter Hines
Peter Hines

Reputation: 1

php cfoutput query group

I am in the process of converting a website from ColdFusion to PHP while learning the latter.

Is there any method in PHP to replicate the the CFOUTPUT Query Group function in PHP? e.g.:

<cfoutput query="clipbook" group="author">

I am trying publish a list of works by different authors, e.g.:

Author one
         Title A
         Title B
Author two
         Title C
         Title D

...and so on.

I have all of the information in a MYSQL data base.

cfoutput query with a group makes it very easy.

Thanks in advance.

Upvotes: 0

Views: 127

Answers (1)

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

A CF query object is technically an array of structs under the hood. PHP sees it in a similar manner. You have to then just loop over the main array and then loop over the inner "nested" data by the column you've identified for grouping. It's just not a simple to implement as with CFML. :)

Here's an example from a post I found:

https://www.garfieldtech.com/blog/php-group-by-with-arrays

<?php
$result = mysql_query("SELECT tid, name, size, color FROM things ORDER BY color, name, size");
$set = array();
while ($record = mysql_fetch_object($result)) {
    $set[$record->name[0]][$record->color][] = $record;
}
ksort($set);
foreach ($set as $letter => $colors) {
    print "<h2>{$letter}</h2>\n";
    foreach ($colors as $color => $record) {
        print "<table>\n";
        print "<caption>{$color}</caption>\n";
        print "<tr><th>Name</th> <th>Size</th> <th>Color</th></tr>\n";
        foreach ($records as $record) {
            print render($record);
        }
        print "</table>\n";
    }
}
?>

Upvotes: 3

Related Questions