Combining results that are the same

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
mchoffa
Forum Newbie
Posts: 2
Joined: Thu Jun 16, 2005 10:57 am

Combining results that are the same

Post by mchoffa »

I have code that accesses a database and gets results based on the a number. Part of the result is a description of features. Right now I have it set up to display each row seperately, but it looks messy if I have ten results with the same type of feature. I want to be able to have it combine all "description"s that have the same "kind" and seperate them by a comma and then move on to the next "kind"... excuse me if I am a little unclear but here is the code

Code: Select all

foreach($frows as $frowix => $frow) {
                        echo "<tr>\n";
                        foreach($frow as $fix => $f) {
                                $kind = $f["kind"];
                                $description = $f["description"];
                                echo "<td><font face=\"verdana\" size=\"1\"><b>$kind:</b> $description</font></td>\n";
                        }
                        echo "</tr>\n";
                }
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

order by description...

and then loop throught he resultset like

Code: Select all

$current_feature = null;

while ($row = mysql_fetch_assoc($rs))
{
  if ($current_feature != $row['feature'])
  {
     // new feature, make heading
     echo "<b>" . $row['feature'] . "</b>";
  }

  // output the row
  print_r($row);
  echo "<br/>";

  $current_feature = $row['feature'];
}
mchoffa
Forum Newbie
Posts: 2
Joined: Thu Jun 16, 2005 10:57 am

Post by mchoffa »

for some reason part of my message disappeared... here is exactly what I need it to do... instead of printing out like this, as it is now:

engine: gm
engine: v6
engine: 350 cu in
transmission: automatic
transmission: 3 speed

I want it to print out the results like this:

engine: gm, v6, 350 cu in
transmission: automatic, 3 speed
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Post by dreamline »

If those values are there for every row that is found then use tables to print the results on your html webpage. The left side for engine info and the right side for transmission info.

Hope this helps you a bit on the right track.. If i need to sort things then i usually do it through tables...

:)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

$current_type = null;
while ($row = mysql_fetch_assoc($result))
{
  if ($current_type != $row['type'])
  {
    // new line has started
    // remove last ,
    $line = rtrim($line, ", ");
    echo $line;  
    echo "<br/>"; 

    $line = $row['type'] . ": ";
  }

  $line .= $row['name'] . ", ";
}
Post Reply