6
\$\begingroup\$

I have a photo list page where each photo has multiple tags (as spaced words). I'm trying to display most of the tags on the page after:

  • Removing duplicate tags
  • Sorting tags by having most occurring tags first

The code looks like this:

$tags1 = "red blue green yellow colors";
$tags2 = "blue green grass tree garden";    
$tags3 = "pink blue colors paint sky"

addTags($tags1);
addTags($tags2);
addTags($tags3);
echo (processTags());

private $tagsArray;
public function addTags($param) {
    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);
    $this->tagsArray = array_merge($this->tagsArray, $explode);
}

private function processTags(){
    $processedTags = array_count_values($this->tagsArray);
    arsort($processedTags);
    $count = 0;
    foreach($processedTags as $tag => $value) { 
        if(++$count>50) break; // don't print more than 50 tags
        $output .= "<a href=\"/tags/$tag\">$tag</a>";
    }
    return $output;
}

Each photo can have dozens of tags and there can be hundreds of tags total. Is there any way to improve the code to make it more efficient? Could it be done with less code? The above code works just fine, but I'm just curious to know if there is a better way to go about it.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I has been a long time since I used PHP, but what you want are multisets that are basically sets with a value -> number-of-occurrences mapping. I believe you can accomplish this in PHP via associative arrays as below:

$tags1 = "red blue green yellow colors blue red green yellow yellow";

function addTags($param) {

    // tagsArray should be a global variable
    // but put as local variable for illustration only
    $tagsArray = array();

    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);

    foreach ($explode as $value) {
       $val = 0;
       if (array_key_exists($value, $tagsArray)) {
          $val = $tagsArray[$value];          
       }

       $tagsArray[$value] = 1 + $val;
    }

    // sort the array
    arsort($tagsArray);

    // for illustration purposes only
    foreach ($tagsArray as $key => $value) {
       echo $key.':'.$value.', ';
    }
}

addTags($tags1);
\$\endgroup\$
1
  • \$\begingroup\$ Thanks Jamal, your editing was very awesome and highly appreciated! Cheers! :) \$\endgroup\$ Commented Nov 23, 2015 at 17:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.