我有一个照片列表页面,其中每张照片都有多个标签(作为间隔的单词)。我试图在以下页面上显示大多数标签:
代码如下所示:
$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;
}
每张照片可以包含数十个标签,总共可以有数百个标签。有没有办法改进代码,使其更加高效?可以用更少的代码完成吗?上面的代码工作正常,但我只是想知道是否有更好的方法去做。