Search code examples
phpmysqlduplicatesarray-unique

how to remove duplicates php array_unique not working


I try using array_unique(); but not working this is my code please help me what i doing wrong? I want display all tags without duplicates

ID | TAGS
1 | rock, punk, jazz
2 | pop, rock, classic
3 | jazz, blues, rock
4 | rock, rap, metal

$wynik = mysql_query("SELECT * FROM nabk_t_item_tags") or die('Błąd zapytania');
if (mysql_num_rows($wynik) > 0) {
    while ($r = mysql_fetch_assoc($wynik)) {
        $input = $r['tags'];
        $fields = explode(',', $input);
        $fields2 = array_unique($fields);
        foreach ($fields2 as $field) {
            echo '"' . $field . '",';
        }
    }
}

Solution

  • Try this code.

    if (mysql_num_rows($wynik) > 0) {
        $used=array();
        while ($r = mysql_fetch_assoc($wynik)) {
            $input = $r['tags'];
            $fields = explode(',', $input);
            foreach($fields as $tg){
                if(!isset($used[$tg])){
                    echo '"' . $tg . '",';
                    $used[$tg]=" ";
                }   
            }
        }
        unset($used);
    }