我有这个数组:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "sbm=SOME_TEXT",
[2] => "obm=SOME_TEXT"
);
如何删除包含值obm
或sbm
的数组元素(它始终位于数组中字符串的顶部)并更新索引?
示例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"
);
答案 0 :(得分:0)
也许是这样的?
$newarray = array_values(array_filter($oldarray, function($value){
return strpos($value, 'obm') !== 0;
}
));
答案 1 :(得分:0)
您可以使用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
)
答案 2 :(得分:0)