在PHP中,如果字符串存在于数组中,则添加“-1”,“ - 2”等,直到唯一

时间:2013-02-01 08:34:27

标签: php arrays string

在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

4 个答案:

答案 0 :(得分:2)

$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;

答案 1 :(得分:1)

这应该有效:

$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
)

答案 2 :(得分:1)

while循环的完美用例:

$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

答案 3 :(得分:0)

我假设你需要在数组中的每个字符串之后附加-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
)