从PHP数组中删除多个元素的有效方法

Fea*_*nne 11 php arrays

我有一个动态生成的文件名数组,让我们说它看起来像这样:

$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file");
Run Code Online (Sandbox Code Playgroud)

我有几个特定的​​文件名,我想从数组中丢弃:

$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";
Run Code Online (Sandbox Code Playgroud)

所以,我总是知道我想要丢弃的元素的值,而不是键.

目前我正在寻找几种方法来做到这一点.一种方法,使用array_filter和自定义函数:

function excludefiles($v)
        {
        if ($v === $GLOBALS['exclude_file_1'] || $v === $GLOBALS['exclude_file_2'])
          {
          return false;
          }
        return true;
        }

$files = array_values(array_filter($files,"excludefiles"));
Run Code Online (Sandbox Code Playgroud)

另一种方法,使用array_keys和unset:

$exclude_files_keys = array(array_search($exclude_file_1,$files),array_search($exclude_file_2,$files));
foreach ($exclude_files_keys as $exclude_files_key)
    {    
    unset($files[$exclude_files_key]);
    }
$files = array_values($page_file_paths);
Run Code Online (Sandbox Code Playgroud)

两种方式都能产生预期的效果.

我只是想知道哪一个更有效(以及为什么)?

或许还有另一种更有效的方法吗?

也许有一种方法可以在array_search函数中有多个搜索值?

Jon*_*Jon 27

你应该简单地使用array_diff:

$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file");
$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";

$exclude = array($exclude_file_1, $exclude_file_2);
$filtered = array_diff($files, $exclude);
Run Code Online (Sandbox Code Playgroud)

关于PHP的一个坏处是,它有数以万计的功能来处理特定的小事情,但有时也会变得方便.

当你遇到这样的情况时(你找到了一个找到相关功能后的解决方案,但你不确定是否有更好的东西),最好在php.net上闲暇浏览功能列表边栏.只是阅读功能名称可以带来巨大的回报.

  • 类似地,如果您需要从关联数组中过滤掉特定键: `$filtered = array_diff_key($arrayToFilter, array_flip(['remove_key_1', 'remove_key_2']));` (2认同)

GoS*_*ash 5

使用 array_diff()

$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file");
$exclude_file_array = array("meta-file-1", "meta-file-2");
Run Code Online (Sandbox Code Playgroud)

将返回一个数组,其中包含 $exclude_file_array 中不在 $files 中的所有元素。

$new_array = array_diff($files, $exclude_file_array);
Run Code Online (Sandbox Code Playgroud)

它比你自己的函数和循环更好。