Group tags separated by PHP comma

Asked

Viewed 218 times

0

Good morning!

Next I have a doubt, and I’m not able to reach conclusion.

I’m creating a field called tag where it serves to search for posts related to tag.

In the bank it is completed as follows;

post1 tag: exemplo1,exemplo2
post2 tag: exemplo3,exemplo2

And how should it be out:

tag: exemplo1,exemplo2,exemplo3

If you notice well, it is separated by a comma. Then I explode to separate string. So far so good.

My question is in the string part repeating equal.

$query = mysqli_query($con, "SELECT tag FROM posts WHERE tag NOT IN('') ");

while($row = mysqli_fetch_array($query)){
  $explode = explode(',',$row['tag']);
  $count = count($explode);
  for($i = 0; $i < $count-1; $i++){
    echo $explode[$i];
  }
}

With this code she’s coming out as follows:

tag: exemplo1,exemplo2,exemplo3,exemplo2

What way to group repeated string?

2 answers

0


I don’t know "mysqli" bad knowing that its return brings all tags grouped can do something like:

$raw = 'exemplo1,exemplo2,exemplo3,exemplo2';
$string = implode(',', array_unique(explode(',', $raw)));
echo $string; // output: exemplo1,exemplo2,exemplo3

I did something like that a while back: Selecting-hashtag-into-database-from-url

  • 1

    Thanks! With your help solved my problem.

0

For whoever wants the code.

$query = mysqli_query($con, "SELECT tag FROM posts WHERE tag NOT IN ('')");

while($row = mysqli_fetch_array($query)){
    $explode = explode(',',$row['tag']);
    $count = count($explode);
    for ($i = 0; $i < $count; $i++) {
        $array .= $explode[$i].',';
    }
}

echo implode(',', array_unique(explode(',', $array)));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.