Reputation: 27
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 . '",';
}
}
}
Upvotes: 1
Views: 1072
Reputation: 1662
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);
}
Upvotes: 0
Reputation: 1395
You have to put all the tags from the query in one single array. So, using your existing code:
// $fields2 = array_unique($fields);
$fields2 = array_merge($fields2, $fields);
Then after the while loop, $fields2
will have all the tags and you can array_unique that array. So, add these lines and see the result:
} // end while
$unique_tags = array_unique($fields2);
var_dump($unique_tags);
} // end if
Upvotes: 1