Jump to content

Grouping query results


Paulkirkewalker

Recommended Posts

Hi there,

I'm relatively new to PHP and mySQL.  I am far more used to using Access and VBA so sorry if I use the wrong terminology here.

In access it is very straightforward, using reports to group the results of a query.  For example, the results:
Paul, Edinburgh
Jo, Glasgow
Nicky, Edinburgh
James, Leeds

can be easily represented like this:
Glasgow
          Jo
Edinburgh
          Nicky
          Paul
Leeds
          James

In Access reports this is called grouping.  I need to do the same in PHP/mySQL to show all the images linked to a parent record together under the parent record's details rather than show each as a seperate result with the parent record's details shown for each image in turn.

Any ideas?

Thanks,
Paul.
Link to comment
https://forums.phpfreaks.com/topic/25157-grouping-query-results/
Share on other sites

put your data in array and try[code]<?php
$data = array(
array('Paul', 'Edinburgh', '1st'),
array('Jo','Glasgow', '2nd'),
array('Nicky', 'Edinburgh', '2nd'),
array('James', 'Leeds', '2nd')
);
function grup($data, $key){
foreach ($data as $a) {
$b = $a[$key];
unset($a[$key]);
$out[$b][] = $a;
}
return $out;
}
function pr($a) {
foreach ($a as $k => $b) {
echo $k,"<br />\n";
foreach ($b as $c) {
echo "- ";
echo implode(' => ',$c);
}
echo "\n<br />\n";
}
echo "<br />\n";
}
pr(grup($data,1));
echo "<hr />\n";
pr(grup($data,2));
?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.