更新列,为重复项添加后缀

时间:2018-10-22 16:17:51

标签: php mysql

title像这样:

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

因此存在重复项(在上述情况下-blue night)。

我需要重命名所有重复项,并在末尾添加-02-03...。

例如第二个{​​{1}}应该是blue night

如果有第三个blue-night-02,则应该为blue night,依此类推。

有帮助吗?

2 个答案:

答案 0 :(得分:1)

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

<?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

答案 1 :(得分:0)

使用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
 )

演示: https://3v4l.org/Hj1Yg