tags:

views:

338

answers:

3
   $content = '<h3>popular tags »</h3><hr>';

    $result = $db->sql_query("SELECT tags FROM ".DOWNLOAD_TABLE." ");
    while($row = $db->sql_fetchrow($result)){
     $dl_tags_id = $row['tags'];
     $dl_tags_id_ex = explode(" ",$dl_tags_id)   ;
     $dl_tags_id = array_unique($dl_tags_id_ex);

     $c = count($dl_tags_id);
     for($i=1;$i<$c-1;$i++){
//for loop content

     }
    }
    echo $content;

Hey guys. I used the above code to show my popular tags. As you can see in the code, I have two tables, one is download table that stores tags ID in array format such as:

20 21 13 14

And the other one is tags table that define those IDs

Now the only problem is that when printing this code, I can see duplicated tags as:

white(2)
blue(4)
white(2)

I wonder how prevent showing duplicated output.

Thanks in advance

A: 

If you have an array you could take a look at php.net.. I think you would have found this: http://nl3.php.net/manual/en/function.array-unique.php This function shows only the unique values of the array.

Bloeper
he already has an example of array_unique in the code he's posted... he's just using it in the wrong spot. I'm not the downvote, though.
Mike Sherov
+2  A: 

this is happening because you're doing the array_unique call on each row!

You're doing this:

while($row = $db->sql_fetchrow($result)){
    $dl_tags_id = $row['tags'];
    $dl_tags_id_ex = explode(" ",$dl_tags_id)   ;
    $dl_tags_id = array_unique($dl_tags_id_ex);
    // rest of code...
}

when really, you want to do this:

$dl_tags_all = '';
while($row = $db->sql_fetchrow($result)){
    $dl_tags_all .= ' '.$row['tags'];
}
$dl_tags_id_ex = explode(" ",substr($dl_tags_all,1));
$dl_tags_id = array_unique($dl_tags_id_ex);
//rest of code....
Mike Sherov
A: 

Not quite sure why you have decided to store multiple data items in one row separated by spaces. If they had been spread over multiple rows this could have been done very easily with a SQL JOIN and using the GROUP BY clause. In fact, you would only have one query instead of several queries as you have now.

For example if your tags table had 10 rows in it, and each tag.tags field had 5 items in it, you would be querying the database 50 times instead of just one query that you would normally perform with a join.

While it's possible to achieve your immediate objective of eliminating duplicates with an array_unique at the proper location as Mike Sherov has pointed out, array_unique is actually adding an additional burden. Now after each iteration of the outer loop your array_unique call means PHP has to internally iterate through all the members of the array to remove dups.

e4c5