update列为重复项添加后缀

m0rkklqb  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(333)

title 是这样的:

gold
blue night
silver morning
about earth 
sun vs king
blue night

因此存在重复项(在上述情况下- blue night ).
我需要重命名所有重复添加 -02 , -03 ... 最后。
例如第二个 blue night 应该是 blue-night-02 如果有第三个 blue night 应该是的 blue-night-03 等等。
有什么帮助吗?

2wnc66cl

2wnc66cl1#

使用数组条目作为计数器非常简单(可能不是最复杂的方法,但可能是):

<?PHP
$str = "gold
blue night
silver morning
about earth 
sun vs king
blue night";

$words = explode("\n",$str);
$matches = array();
$wordsConverted = array();

foreach($words as $word)
{
    if(isset($matches[$word]))
    {
        if($matches[$word] > 10)
        {
            $wordsConverted[] = $word.'-'.$matches[$word]++;
        }
        else
        {
            $wordsConverted[] = $word.'-0'.$matches[$word]++;
        }

    }
    else
    {
        $matches[$word] = 2;
        $wordsConverted[] = $word;
    }
}

foreach($wordsConverted as $convertedWord)
{
    echo $convertedWord."</br>";
}

?>

输出:

gold
blue night
silver morning
about earth
sun vs king
blue night-02
relj7zay

relj7zay2#

更简洁的使用方法 array_count_values() ,

<?php
$title = ['gold','blue night','silver morning','about earth','sun vs king','blue night','about earth','gold','about earth'];

$value_counts = array_count_values($title);

# print_r($value_counts);

$expected_result = [];
foreach($value_counts as $k=>$v){
    if($v<2){
        $expected_result[] = $k;
    }else{
        $expected_result[] = $k;
        for($i=2;$i<=$v;$i++){
            $expected_result[] = $k."-".$i; 
        }
    }
}

print_r($expected_result);

输出:

Array ( 
  [0] => gold
  [1] => gold-2
  [2] => blue night
  [3] => blue night-2
  [4] => silver morning 
  [5] => about earth
  [6] => about earth-2 
  [7] => about earth-3 
  [8] => sun vs king
 )

demo:https网址:http://3v4l.org/hj1yg

相关问题