search
HomeBackend DevelopmentPHP TutorialThinkPHP添加更新标签的方法_php实例

本文实例讲述了ThinkPHP添加更新标签的方法。分享给大家供大家参考。具体分析如下:

我们知道,thinkphp的拓展案例blog,只告诉我们怎样去添加标签tag,却没有删除和更新标签的方法,我在前面的《彻底删除thinkphp3.1案例blog标签的方法》为拓展案例blog写了一个删除标签的方法,接下来将写一个标签的更新方法.

一般情况下,我们写博客后,很少去改动标签了,但是如果我们改动标签如,删除,添加,减少标签怎么办呢?这无疑造成think_tag和think_tagged两个表垃圾信息的积累,好了,言归正转.

在更新标签时我们来了解两个参数:

$oldtags:更新前,存在thinphp_tag表中标签

$newstags:更新时,插入thinphp_tag之前,表单提交过来的标签

更新文章时,标签可能会有以下几种变化:

1、$newstags与$oldtags部分相同-> 添加或减少或修改标签,标签的个数和名称和原来部分相同。

2、$newstags与$oldtags完全相同->不修改标签

3、$newstags与$oldtags完全不同 ->添加或减少标签,并且标签的个数和名称和原来完全不同

对于2我们只要通过判断比较过滤即可,对于1、3通过判断比较后,再作删除或添加处理:

删除:要删除的标签名,在thinphp_tag已存在,当标签的count=1时,就把它删除掉,当count>1时,就减少1(count-1).

添加:要添加的标签名称,如果thinphp_tag表中已存在则count(count >1)在原来的基础上+1即count+1,如果不存在(count =0),则添加新标签,count+1.具体函数如下:

复制代码 代码如下:
public function updateTag($vo,$module) { 
 $recordId= trim($vo['id']); 
 
if($vo['keywords']==''){//如果没有标签,则把原来的标签删除 
     $this->deltag($recordId);     
   }else{ 
      $newtags = explode(' ', $vo['keywords']);//获取更新的标签并转为数组(keywords是这里的标签字段,在thinkphp的拓展案例blog为tags,注意)
 
   $condition['recordId'] = $recordId;//当有多个标签时,将查询多篇日记,而不是一篇 
 
 $tagged=M('Tagged'); 
 
  $tag=M('Tag');          
 
  $taggedlist= $tagged->where($condition)->select(); 
 
if($taggedlist !==false){ 
 
foreach ($taggedlist as $key => $value) { 
 
  $tagId=trim($value['tagId']); 
 
  $tagvo=$tag->where('id='.$tagId)->find(); 
 
  $oldtags[]=$tagvo['name'];//获取原来的标签 
 
  }    
 
   $result=count(array_diff(array_diff($newtags,$oldtags),array_diff($oldtags,$newtags)));     
 
   $result1=count(array_diff($newtags,$oldtags));//返回更新前后TAG的差值数 
 
  $result2=count(array_diff($oldtags,$newtags));//返回更新前后TAG的差值数
 
  if(($result1 !== $result2) || ($result !==0)){//2与原来的完全相同->过滤掉            
 
   $array_intersect=array_intersect($oldtags,$newtags);//取得交值 
 
   $oldtags_diff=array_diff($oldtags,$array_intersect);//原来的标签,被更新后已无用,需要删除的 
 
    $newtags_diff=array_diff($newtags,$array_intersect);//修改的标签,需要添加的 
 
//删除或者count-1    
 
     if(count($oldtags_diff) !==0){  
 
     foreach ($oldtags_diff as $name) { 
 
     $tagvo=$tag->where("module='$module' and name='$name'")->find(); 
 
     $count=intval($tagvo['count']);//获取标签的数量 
 
if($count==1){ 
 
    $tag->where('id='.$tagvo['id'])->delete(); 
 
    $tagged->where('tagId='.$tagvo['id'].' and recordId='.$recordId)->delete(); 
 
 }elseif($count > 1){ 
   $tag->where('id='.$tagvo['id'])->setDec('count',1);//标签数量减1 
 
   $tagged->where('tagId='.$tagvo['id'].' and recordId='.$recordId)->delete();//删除tagged中相关数据  
 }
  }

//添加更新的标签   
 
if(count($newtags_diff) !==0){ 
 
   foreach ($newtags_diff as $v) { 
 
       $v = trim($v);          
 
       if (!emptyempty($v)) { 
 
        // 记录已经存在的标签 
 
     $map['module'] = $module; 
 
        $map['name'] = $v; 
 
        $tagg = $tag->where($map)->find(); 
 
       if ($tagg) {//如果现在保存的标签与之前相同的标签累加 
 
       $tagId = $tagg['id']; 
 
          $tag->where('id=' . $tagg["id"])->setInc('count', 1);//count统计加1(这个函数有三个参数,默认加1) 
 
          } else {//如果是新添的标签,标签+1 
 
                   $t = array(); 
 
                   $t["name"] = $v; 
 
                   $t["count"] = 1; 
 
                   $t["module"] = $module; 
 
                   $result = $tag->add($t); 
 
                   $tagId = $result; 
 
            } 
      } 
                 //记录tag信息 
    $t = array(); 
 
      $t["module"] = $module; 
 
      $t["recordId"] = $recordId;//保存news的ID 
 
      $t["tagTime"] = time(); 
 
      $t["tagId"] = $tagId;//保存tag的ID 
 
      $tagged->add($t); 
 
     } 
 
    }  
     } 
     } 
     } 
}

使用方法:
复制代码 代码如下:
public  function update() { 
$Blog=D('Blog'); 
$vo=$Blog->create(); 
$this->updateTag($vo,'Blog');//更新前调用 
if (false === $vo) { 
 $this->error($Blog->getError()); 
     } 
   // 更新数据 
   $list = $Blog->save(); 
   if (false !== $list) { 
     //print_r($list); 
      
     $this->success('编辑成功!'); 
   } else { 
       //错误提示 
       $this->error('编辑失败!'); 
   } 
}

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)