How do i merge matching strings in an array?

72 Views Asked by At

Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.

    function get_tags()
{
    $tag_array = array();
    $query = mysql_query("
    SELECT tags 
    FROM gallery_image
    ");

    while($row = mysql_fetch_assoc($query))
    {
        $tags = $row['tags'];
        $tag_array[] = $tags;

    }

    echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
3

There are 3 best solutions below

0
On BEST ANSWER

You question is not very clear but array_unique may be what you need?

function get_tags()
{
  $query = mysql_query('SELECT tags '.
                       'FROM gallery_image');
  $tag_array = array();
  while($row = mysql_fetch_assoc($query))
    $tag_array = array_merge($tag_array, explode(',', $row['tags']));

  return array_unique($tag_array);
}
0
On

You probably want something like this:

$tags = array(
    'one,two',
    'one,three',
);

$result = array_unique(array_reduce($tags, 
                                    function($curr, $el) {
                                        return array_merge($curr, explode(',', $el));
                                    },
                                    array()));

See it in action.

What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.

0
On

Try this:

$unique_tags = array();
foreach ($tag_array as $value) {
    $unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);