Question : Dedupe a mysql output using php

Hi,

I'm trying to figure out how to dedupe a query that I call using php that gives me duplicates. The reason being is because the ID from the main table has a one-to-many relationship with another table.

So when I

select main.column, other.column from main, other where main.ID=other.foreignkey;

I get this result:

fruit apple
fruit lemon
fruit grape
meat chicken
meat beef

I want to get rid of the duplicates in the first column. Well, not only the first because in reality I have a join where I'm using multiple tables and I don't want duplicates in those columns either.

So basically what I'm saying is I want to be able to print out 1 row per result for every column except the column from that one table.

example:

fruit     juice     red         tree      apple
                                                      lemon
                                                      grape
meat    sauce   brown   animal   chicken
                                                          beef

This is what I'm using to ouput the query:

echo "<table>";

        while($row = mysql_fetch_row($query)) {
                echo "<tr'>";
                foreach ($row as $str) {
                        echo "<td>".$str."</td>";
                }
                echo "</tr>";
        }
        echo "</table>";


I tried, and failed to do it using mysql so I'm trying now with php.  Can anybody help me out with this please? Is it clear what I'm asking for?

Answer : Dedupe a mysql output using php

Really you should be using a join if you are using a key from one table to another, but to follow what you have now you could do something like the following:

select main.column as main, group_concat(other.column) as other from main, other where main.id=other.id group by main.column;

which would return something like the following:


+------+--------------------------+
| main | other                           |
+------+--------------------------+
| fruit   | apple,pear,lemon        |  
| meat | cow,pig                       |
+------+--------------------------+

you could then use <?php explode(',' , $result[other]) ?> to turn it into an array for however you want to use it.

best of luck!
Random Solutions  
 
programming4us programming4us