列 title 是这样的:
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 等等。有什么帮助吗?
blue night
-02
-03
blue-night-02
blue-night-03
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
relj7zay2#
更简洁的使用方法 array_count_values() ,
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
2条答案
按热度按时间2wnc66cl1#
使用数组条目作为计数器非常简单(可能不是最复杂的方法,但可能是):
输出:
relj7zay2#
更简洁的使用方法
array_count_values()
,输出:
demo:https网址:http://3v4l.org/hj1yg