新手问题-我正在尝试删除以'not__'开头的键的元素。它的内部laravel项目,因此我可以使用它的数组函数。我正在尝试在循环后删除元素。这不会删除任何内容,即不起作用:
function fixinput($arrinput)
{
$keystoremove = array();
foreach ($arrinput as $key => $value);
{
if (starts_with($key, 'not__'))
{
$keystoremove = array_add($keystoremove, '', $key);
}
}
$arrinput = array_except($arrinput, $keystoremove);
return $arrinput;
}
Run Code Online (Sandbox Code Playgroud)
请注意,它不是阵列上的唯一任务。我会自己尝试的。:)
谢谢!
$filtered = array();
foreach ($array as $key => $value) {
if (strpos($key, 'not__') !== 0) {
$filtered[$key] = $value;
}
}
Run Code Online (Sandbox Code Playgroud)
使用带有标志的array_filter函数ARRAY_FILTER_USE_KEY看起来是最好/最快的选项。
$arrinput = array_filter( $arrinput, function($key){
return strpos($key, 'not__') !== 0;
}, ARRAY_FILTER_USE_KEY );
Run Code Online (Sandbox Code Playgroud)
直到版本 5.6.0 才添加标志参数,因此对于旧版本的 PHP,for 循环可能是最快的选择。
foreach ($arrinput as $key => $value) {
if(strpos($key, 'not__') === 0) {
unset($arrinput[$key]);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为以下方法要慢得多,但它只是一种不同的方法。
$allowed_keys = array_filter( array_keys( $arrinput ), function($key){
return strpos($key, 'not__') !== 0;
} );
$arrinput = array_intersect_key($arrinput , array_flip( $allowed_keys ));
Run Code Online (Sandbox Code Playgroud)
功能
if(!function_exists('array_remove_keys_beginning_with')){
function array_remove_keys_beginning_with( $array, $str ) {
if(defined('ARRAY_FILTER_USE_KEY')){
return array_filter( $array, function($key) use ($str) {
return strpos($key, $str) !== 0;
}, ARRAY_FILTER_USE_KEY );
}
foreach ($array as $key => $value) {
if(strpos($key, $str) === 0) {
unset($array[ $key ]);
}
}
return $array;
}
}
Run Code Online (Sandbox Code Playgroud)