Pulling out only the unique tags from all records
3 posts by 2 authors in: Forums > CMS Builder
Last Post: July 5, 2017 (RSS)
By hiroko - June 30, 2017
Hello,
Can anyone help me with sorting my unique tags?
I have a field called 'tags' in the 'news' section where I can put in words separating them by commas.
Now I am wondering if it is possible to list only the unique ones from all of the records from the 'news' section to display on the sidebar.
This is the code I have for each record.
<?php foreach ($newsRecords as $record): ?>
<?php $tagList = explode(',', $record['tags']); ?>
<?php ksort($tagList); ?>
<?php foreach ($tagList as $tagLink): ?>
<a href="<?php echo PREFIX_URL ?>/search-result.php?q=<?php echo $tagLink ?>&input=Search"><?php echo $tagLink ?></a>
<?php endforeach ?>
<?php endforeach ?>
I was thinking of using the unique_array but I guess I need to merge all the exploded tags listed first and I can't figure out how to do this.
Thank you for your help.
Hiroko
By Dave - July 5, 2017
Hi Hiroko,
Try this:
<?php
// get sorted unique tag list
$tagList = [];
foreach ($newsRecords as $record) {
$recordTags = explode(',', $record['tags']);
foreach ($recordTags as $tag) { $tagList[] = $tag; }
}
$tagList = array_unique($tagList);
natcasesort($tagList);
?>
<?php foreach ($tagList as $tagLink): ?>
<a href="<?php echo PREFIX_URL ?>/search-result.php?q=<?php echo urlencode($tagLink) ?>&input=Search"><?php echo htmlencode($tagLink) ?></a>
<?php endforeach ?>
Let me know if that works for you!
interactivetools.com