在 PHP 中,如果数组中存在字符串,请添加 '-1'、'-2' 等,直到唯一


In PHP, If string exists in array, add '-1', '-2', etc, until unique

在PHP中,我需要检查数组中是否存在字符串。如果是这样,则应在其值中添加"-1",如果"string-1"再次存在,则它应该是"string-2"等,直到"string-N"是唯一的。

$string = 'string';
If $string exists in $array, $string = 'string-1'
If $string exists again in $array, $string = 'string-2'
If $string exists again in $array, $string = 'string-3'
etc
$filearray = //blah blah ... (you need to have this array filled before)
$filename = "string";
if (in_array($filename,$filearray))
{
    $i = 1;
    while (in_array($filename.'-'.$i,$filearray))
    {
        i++;
    }
    $filename = $filename.'-'.$i;
}
echo $filename;

这应该有效:

$array = array("this", "is", "my", "string", "and", "it", "is", "a", "string");
$string = "string";
$i = 1;
foreach ($array as &$value) {
    if ($value == $string) {
        $value = $string . "-" . ($i++);
    }
}
unset($value);

输出:

Array
(
    [0] => this
    [1] => is
    [2] => my
    [3] => string-1
    [4] => and
    [5] => it
    [6] => is
    [7] => a
    [8] => string-2
)

while-loops 的完美用例:

$tmp = $string;
$i = 1;
while(in_array($tmp, $array)) {
    $tmp = $string . '-' . $i;
    ++$i;
}
$string = $tmp;

例:

$string = 'test';
$array = ['foo', 'bar', 'test', 'test-1'];

输出:

test-2

我假设你需要在数组中的每个字符串之后附加 -1, -2...,如果它有多个出现。检查此代码:

<?php
$array = array("this", "is", "my", "string", "and", "it", "is", "a", "string", "do", "you", "like", "my", "string");
$ocurrences = array();
$iterator = new ArrayIterator($array);
while ($iterator->valid()) {
    $keys = array_keys($ocurrences);
    if (in_array($iterator->current(), $keys)) {
        $array[$iterator->key()] = $iterator->current() . '-' . $ocurrences[$iterator->current()];
        $ocurrences[$iterator->current()]++;
    }
    else {
        $ocurrences[$iterator->current()] = 1;
    }
    $iterator->next();
}
print_r($array);

它将打印:

Array
(
    [0] => this
    [1] => is
    [2] => my
    [3] => string
    [4] => and
    [5] => it
    [6] => is-1
    [7] => a
    [8] => string-1
    [9] => do
    [10] => you
    [11] => like
    [12] => my-1
    [13] => string-2
)