Question

I am trying to create a simple tag cloud in PHP. The following is what I have so far but its not working because I have no idea what I'm doing.

For each record in the database, tags are stored like this: tag1,tag2,tag3 etc... So I have to somehow get the records first and them break then into individual tags and display them that way. Any help would be greatly appreciated.

// DB: get snippet tags
$get_snippet_tags = mysqli_query($conn, "SELECT Tags FROM snippets WHERE IsPublic = 1 LIMIT 20")
or die($dataaccess_error);

if(mysqli_num_rows($get_snippet_tags) > 0 )
{
    while($row = mysqli_fetch_array($get_snippet_tags))
    {
        $snippet_tags = $row['Tags'];

        // explode tags
        $tags_array = array_map('string', $snippet_tags);
        $cloud_tag = implode(", ", $tags_array);

        // echo out resluts
        echo '<a href="#">'.$tags_array.'</a>';
    }
}
Was it helpful?

Solution

begin by using

explode('separator','string'); like explode(',',$row['Tags']);

this will make your string in to an array separated by ','.

push each array you get (from explode) to an array.

then create a function like:

 function value_occurs($arr) { 
      $arr2=array(); 
      if(!is_array($arr['0'])){$arr=array($arr);} 
         foreach($arr as $k=> $v){ 
            foreach($v as $v2){ 
               if(!isset($arr2[$v2])){ 
                   $arr2[$v2]=1; 
               }else{ 
                   $arr2[$v2]++; 
            } 
         } 
     } 
     return $arr2; 
 }

and call it

$result = value_occurs($theArrayWithAllTheTags);<br>

this will return an array with your tagname as key and your count as value

OTHER TIPS

It's not an array yet. Use explode() to split by commas.

http://php.net/manual/en/function.explode.php

$tagsArray = explode(",", $tags);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top