blog about graphic design, web design and marketing

The D. Drew Design Blog
27
jun 09

PHP Popular Tags List

A popular tags list can help your users find articles relating to certain topics without having to guess what a good search input might be. This is the code I created for my own site, which now contains one such list.

First, you have to make sure your content is tagged appropriately. That means when it's uploaded to the database, it also has a tag or keyword section in each row. In my case, I accessed the database with this entry:


// Replace these values with your own.
$result = @mysql_query('SELECT keywords FROM yourtable ORDER BY ID DESC');


Notice I'm only taking the keywords from the postings table. That's all I need. No point in extracting extra information from the table if it's not going to be used.

Next comes the PHP. You can copy and paste this code, which should work for anyone who has the proper field in their database.


$listarray = array();
while($row = mysql_fetch_array($result))
{
    // Replace 'keywords' with the name of the field in your database
    // and use whatever delimiter you are using to separate the names
    // in your field. In my case, it's a comma.
    $rowarray = explode(',', $row['keywords']);

    // Set a loop, assign the keyword to a variable
    foreach($rowarray as $rowkeyword)
    {
        // Set the trigger in case it gets to the end without setting count
        $notfound = true;

        // Set a loop, assign keyword and counts as variables in each iteration
        foreach($listarray as $listkeyword => $count)
        {
            // If the keyword supplied matches this iteration, add 1.
            if($rowkeyword == $listkeyword)
            {
                $count++;
                $listarray[$listkeyword] = $count;
                $notfound = false;
                break;
            }
        }

        // If you've gone through the whole listarray and not found one, make one
        if($notfound)
        {
            $listarray[$rowkeyword] = 1;
        }
    }
}


I'd recommend reading the code and its comments to understand the process, but here's a quick rundown: It's creating an array that will eventually contain indexes that are the names of the various keywords in your database, and their values will be the number of times those keywords appear in your database, by way of the following steps:

  1. It's separating out your keywords in each individual row (or entry). For instance, in this article, my keywords are php, code, tutorial and keywords. In this section of the code, it is turning these keywords into an array [0]=>php, [1]=>code, etc.

  2. I am then setting two loops. The first loop will go through each of this particular row's keywords (the ones I mention above). The second loop will loop through all the keywords established as indexes in the keyword-counting array. In other words, Loop 1 is simply picking keywords to compare to its inner loop, which is going through all of its array items to make sure none of the items in Loop 1 are in there.

  3. Since there doesn't seem to be a way for PHP to know that it's on the last iteration of an array, I have to create a catcher that will perform an operation if the inner loop break isn't executed. That's what the $notfound variable is for. If, through checking the inner loop, there turns out to be no matches found between the row and list keywords, I've established an 'if' statement to add that keyword to the keyword list with the value of '1' (as there is at least 1 iteration of an article with this keyword).

  4. If it turns out that the keyword does already have an index in the keyword list, then we take whatever current value it has and add 1 to it denoting another instance of this keyword. We then end the inner loop with a 'break' as there's no need to further loop through if we've found a match. There should only be 1 match.

  5. Once this function has finished processing, you get a complete $listarray, which has indexed all of the keywords or tags that you have, and has assigned them each a count of the number of times they appeared in your database.


What you do at this point is entirely up to you. If you want an example, here's what I did:


// Sorts array by its values, in ascending order, then reverses the order,
// both while maintaining the indices.
asort($listarray);
$listarray= array_reverse($listarray, true);

$i = 1;
$keywordstring = '<ul>';

foreach($listarray as $keywordlink => $appearances)
{
    // Outputs HTML of array in list form, then echoes it.
    $keywordstring .= '<li><a href="/home.php?cmd=topic&keyword=' . $keywordlink . '" class="bodyLink">' . $keywordlink . ' </a><span>' . $appearances . '</span>';

    // Up to 10 keywords. You can set this as high as you want, though
    // you should probably limit it, unless you're using a cloud of tags
    // or some other format that would benefit from seeing all keywords.
    $i++;
    if($i > 10)
    {
        break;
    }
}

$keywordstring .= '</ul>';
echo $keywordstring;


If you opt to sort the array by the counts, make sure you use asort(). Regular sort() will replace your keywords. Also, this sets it in ascending order, so if you want, instead, for the array to go in descending order, use the array_reverse() function. You won't be able to put the asort() function inside of the array_reverse() function as it doesn't return a variable. It simply changes the variable sent to the asort() function. Also, make sure you set the second value in array_reverse() to 'true', otherwise, it will reset your indexes to numbers.

The rest is pretty standard. Design it to your liking. The key thing here is that, after the first process, you'll have a clean list of keywords and the number of times they appear. You can set an algorithm that figures out the max iterations versus the minimum iterations and dynamically generates the style of the final output. You know, if you really wanted to.

If you have any questions, feel free to e-mail me.

top categories of graphic design, web design and marketing articles, listed from most frequent



graphic design, website design, and marketing articles listed by date, started from most current, and organized by articles per each month