Help with numbering groups

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gavin1211
Forum Newbie
Posts: 6
Joined: Thu Nov 04, 2010 12:47 pm

Help with numbering groups

Post by gavin1211 »

Hello, I have a newbie problem and I don't know where to start. Basically I have a table which consists of car details. For example it is structured like:

Make | Model
-----------------
Audi | TT
Audi | TT
BMW | X5
Ford | Mondeo
BMW | 5 Series
Audi | A8
Ford | Mustang

I want to out put values from this table based on their make. But I would like with php to somehow detect the first make and number them 1, 2 , 3 ..., based on the make. Kind of like grouping the makes and numbering them within that group. For example:

1 Audi TT
2 Audi TT
3 Audi A8
1 Ford Mondeo
1 BMW X5
2 BMW 5 Series
1 Ford Mustang

Please can somebody point me in the right direction.

Thanks
s992
Forum Contributor
Posts: 124
Joined: Wed Oct 27, 2010 3:06 pm

Re: Help with numbering groups

Post by s992 »

The easiest way to do it would be to add another column to your table with the name "quantity." Then you only have one row per make/model and can easily see the quantity of each.
mikecampbell
Forum Commoner
Posts: 38
Joined: Tue Oct 12, 2010 7:26 pm

Re: Help with numbering groups

Post by mikecampbell »

Inside the loop where you are printing out the cars, keep an associative array. Roughly, it would look like this.

Code: Select all

if (isset($counter[$make]))
   $make_count = $counter[$make]+1;
else
   $make_count = 1;

echo $make_count;

$counter[$make] = $make_count;
gavin1211
Forum Newbie
Posts: 6
Joined: Thu Nov 04, 2010 12:47 pm

Re: Help with numbering groups

Post by gavin1211 »

Thanks for the responses, thanks Mike, I tried that but unfortunately I cant get this to work. The code I am using is below:

Code: Select all

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ 
    $row = mysql_fetch_assoc($resultID);
	 
	
	$make = ;

if (isset($counter[$make]))
   $make_count = $counter[$make]+1;
else
   $make_count = 1;
		 
   $xml_output .= '<category 
   
   title="'. $row['Make'] .' '. $row['Model'] .'" model="'. $row['Make'] .'" 
   year="'. $row['Year'] .', " 
   mileage="'.$row['Mileage'].' miles" 
   trans="'.$row['Fuel'].' '.$row['Transmission'].'" 
   price="'. $row['Price'] .'"
   total="'.$num_rows.'"
   refer="'. $make_count .'"
   
   >';
Any ideas what I am doing wrong?

Much appreciated
gavin1211
Forum Newbie
Posts: 6
Joined: Thu Nov 04, 2010 12:47 pm

Re: Help with numbering groups

Post by gavin1211 »

Mike Campbell, you are an absolute hero, your advice worked perfectly. :D

Thanks a million
Gavin
Post Reply