3
Jan

Convert Comma Separated Values to Links with PHP/MySQL

I’m displaying a list of tags on my site which are formatted as Comma Separated Values (CSV) for every post. Example above.

The CSV tags are stored in the MySQL database as one long string. I wanted to make each tag a link that goes to the search page.

Example: search.php?tag=robots

I found that I can explode the CSV into an array to split it up, then print out the list which basically gives me what I started with. What I had problems with is formatting the array to add the links. That’s where this link from php.net became handy.

http://us2.php.net/manual/en/function.implode.php#83464

I modified the script to explode my CSV from the database:


function myImplode($before, $after, $glue, $array){
$nbItem = count($array);
$i = 1;
foreach($array as $item){
if($i < $nbItem){
$output .= "$before$item$after$glue";
}else $output .= "$before$item$after";
$i++;
}
return $output;
}
$an_array = explode(', ',$stringofCSV);
print myImplode("","",", ", $an_array);

Then I took it a step further to add the values as search parameters. That involved splitting up the function into more pieces so I could insert the values. Simply adding the $an_array variable after the tag= didn’t loop through the values.

Code Example:


function myImplode($before, $array, $before2, $after, $glue, $array){
    $nbItem = count($array);
    $i = 1;
    foreach($array as $item){
        if($i < $nbItem){
            $output .= "$before$item$before2$item$after$glue";
        }else $output .= "$before$item$before2$item$after";
        $i++;
    }
    return $output;
}
$an_array = explode(', ',$stringofCSV);
print myImplode("","",", ", $an_array);

Conclusions: The more popular method may be to add the CSV as individual database entries and then pull them up one by one, but for my purposes this worked just fine.

14 Perspectives © 2012. Some Rights Reserved.