Jump to content


Photo

Grouping query results


  • Please log in to reply
1 reply to this topic

#1 Paulkirkewalker

Paulkirkewalker
  • Members
  • PipPip
  • Member
  • 15 posts

Posted 26 October 2006 - 10:58 AM

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.

#2 sasa

sasa
  • Staff Alumni
  • Advanced Member
  • 2,804 posts
  • LocationHrvatska

Posted 27 October 2006 - 06:49 AM

put your data in array and try
<?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));
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users