Search code examples
phparraysmappingtag-cloud

Create a tag cloud by wrapping array values in h1 through h6 tags based on a mapping array of weights


I have the following arrays:

$artist = ["the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"];
$count = [5, 3, 9, 1, 1, 3];

I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags.


Solution

  • You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds http://drupal.org/project/tagadelic):

    db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');
    
    $steps = 6;
    $tags = array();
    $min = 1e9;
    $max = -1e9;
    
    while ($tag = db_fetch_object($result)) {
        $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it
        $tag->count = log($tag->count);
        $min = min($min, $tag->count);
        $max = max($max, $tag->count);
        $tags[$tag->tid] = $tag;
    }
    // Note: we need to ensure the range is slightly too large to make sure even
    // the largest element is rounded down.
    $range = max(.01, $max - $min) * 1.0001;
    
    foreach ($tags as $key => $value) {
        $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range);
    }
    

    Then in your view or template:

    foreach ($tags as $tag) {
        $output .= "<h$tag->weight>$tag->name</h$tag->weight>"
    }