PHP - 检查数组中的重复项并更新循环中的重复值

时间:2016-02-21 07:14:49

标签: php arrays regex

$mymarker = '/MARKER[0-9]{2}/';
preg_match_all($mymarker, $mycontent, $matches);
var_dump($matches);

给出:

array(1) {
  [0]=>
  array(18) {
    [0]=>
    string(8) "MARKER00"
    [1]=>
    string(8) "MARKER01"
    [2]=>
    string(8) "MARKER02"
    [3]=>
    string(8) "MARKER04"
    [4]=>
    string(8) "MARKER05"
    [5]=>
    string(8) "MARKER07"
    [6]=>
    string(8) "MARKER09"
    [7]=>
    string(8) "MARKER13"
    [8]=>
    string(8) "MARKER13"
    [9]=>
    string(8) "MARKER16"
    [10]=>
    string(8) "MARKER15"
    [11]=>
    string(8) "MARKER21"
    [12]=>
    string(8) "MARKER31"
    [13]=>
    string(8) "MARKER22"
    [14]=>
    string(8) "MARKER24"
    [15]=>
    string(8) "MARKER26"
    [16]=>
    string(8) "MARKER80"
    [17]=>
    string(8) "MARKER81"
  }
}

如我们所见,MARKER13出现两次。 MARKER05,MARKER07和MARKER13可以发生这种重复的实例。

需要将第二个值更新为MARKERXX + 1 第二次出现:

Marker05必须更新为MARKER06 Marker07必须更新为MARKER08 MARKER13必须更新为MARKER14。

我们如何在循环中设置它,检查重复并将重复值更新为下一个值。

由于

1 个答案:

答案 0 :(得分:2)

可能有更简单的方法,但您可以提出以下

<?php
$matches = array("MARKER00","MARKER01","MARKER02","MARKER04","MARKER05","MARKER07","MARKER09","MARKER13","MARKER13","MARKER16","MARKER15","MARKER21","MARKER31","MARKER22","MARKER24","MARKER26","MARKER80","MARKER81");

$duplicates = array("MARKER05", "MARKER07", "MARKER13");
$len = count($matches);

for ($i=0;$i<$len;$i++) {
    $marker = $matches[$i];

    if (in_array($marker, $duplicates)) {
        // one of our markers
        // check if the next is the same
        // if so update it
        if ($i<$len-1) {
            if ($marker == $matches[$i+1]) {
                # split the string into a letter and a digit part
                # with lookarounds (behind/ahead, both positive)
                list($text,$number) = preg_split('~(?<=[A-Z])(?=\d)~', $matches[$i+1]);
                $number = intval($number);
                # increase the intval'd number by one
                # and apply it to the original array
                $number += 1;
                $matches[$i+1] = $text . $number;
            }
        }
    }
}

print_r($matches);
// updated to MARKER14

?>

显然,这只有在数组被排序时才有效,即重复跟进。