0

我有这个数组:

$array = array(
    [0] => "obm=SOME_TEXT",
    [1] => "sbm=SOME_TEXT",
    [2] => "obm=SOME_TEXT"
);

如何删除包含值obmsbm(始终位于数组中字符串的顶部)的数组元素并更新索引?

示例 1:

print_r(arrRemove("smb", $array));

输出:

$array = array(
    [0] => "obm=SOME_TEXT",
    [1] => "obm=SOME_TEXT"
);

示例 2:

print_r(arrRemove("omb", $array));

输出:

$array = array(
    [0] => "sbm=SOME_TEXT"
);
4

3 回答 3

0

这是由 PHP 处理的

php.net/manual/en/function.array-pop.php

array_pop() 弹出并返回数组的最后一个值,将数组缩短一个元素。

于 2013-10-13T12:47:52.457 回答
0

也许是这样的?

$newarray = array_values(array_filter($oldarray, function($value){
    return strpos($value, 'obm') !== 0;
}
));
于 2013-10-13T10:36:08.543 回答
0

您可以简单地使用 a 遍历数组foreach,然后使用它strpos()来检查数组是否包含给定的输入字符串,并array_values()更新索引:

function arrRemove($str, $input) {
    foreach ($input as $key => $value) {            
        // get the word before '='
        list($word, $text) = explode('=', $value); 

        // check if the word contains your searchterm
        if (strpos($word, $str) !== FALSE) {
            unset($input[$key]);
        }
    }
    return array_values($input);
}

用法:

print_r(arrRemove('obm', $array));
print_r(arrRemove('sbm', $array));

输出:

Array
(
    [0] => sbm=SOME_TEXT
)

Array
(
    [0] => obm=SOME_TEXT
    [1] => obm=SOME_TEXT
)

演示!

于 2013-10-13T10:36:21.143 回答