SimonLeCat SimonLeCat - 1 year ago 67
MySQL Question

PHP array_unique returns duplicate

This is my table


| id| tag|
| 1 | dance,|
| 2 | dance,tecno,|
| 3 | dance,hihop,|
| 4 | rap,|
| 5 | country,|
| . | ...|

I tried this (
is my query):

$tags = $this->db->query(sprintf("SELECT `tag`, `id` FROM `tracks` WHERE `tag` LIKE '%s' GROUP BY `tag` DESC LIMIT %s, %s", '%'.$this->db->real_escape_string($value).'%', $this->db->real_escape_string($start), $per_page));

while($row = $tags->fetch_assoc()) {
$rows[] = $row;

$tags = explode(',', $row['tag']);
$rows = array_unique(array_map('strtolower', $tags));

foreach($rows as $row) {
if(stripos($row, $value) !== false) {
$tag_output .= '<div class="hashtag-inner">

From this Eg. the output expected was:
dance, tecno, hiphop, rap, country
with all unique tags instead I have multiple output for the tag
What's wrong with my output?

Answer Source

You need to call explode() in the loop that processes each row. Your code is just exploding the last row.

$rows = array();
while ($row = $tags->fetch_assoc()) {
    $tags = explode(',', $row['tag']);
    $rows = array_merge($rows, $tags);
$rows = array_unique(array_map('strtolower', array_filter($rows)));

array_filter() is used to remove the empty strings that come from the , at the end of the tag lists.

However, the best long-term solution would be to normalize your database schema so you don't store comma-separated lists in the table. You should have a table where each tag is in a separate row.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download