-1

在 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

4 回答 4

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;
于 2013-02-01T08:41:08.767 回答
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
)
于 2013-02-01T08:38:17.403 回答
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
于 2013-02-01T08:39:06.890 回答
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
)
于 2013-02-01T09:09:31.123 回答