我有一个动态生成的文件名数组,让我们说它看起来像这样:
@H_403_1@$files = array("a-file","b-file","Meta-file-1","Meta-file-2","z-file");
我有几个特定的文件名,我想从数组中丢弃:
@H_403_1@$exclude_file_1 = "Meta-file-1"; $exclude_file_2 = "Meta-file-2";所以,我总是知道我想要丢弃的元素的值,而不是键.
目前我正在考虑几种方法来做到这一点.
一种方法,使用array_filter和自定义函数:
另一种方式,using array_keys and unset:
@H_403_1@$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);两种方式都能产生预期的效果.
我只是想知道哪一个更有效(以及为什么)?
或许还有另一种更有效的方法可以做到这一点?
你应该简单地使用
array_diff
:
@H_403_1@$files = array("a-file","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);
关于PHP的一个坏处是它有数以万计的函数来执行特定的小事情,但有时也会变得方便.
当你遇到这样的情况时(你找到了一个找到相关功能后的解决方案,但你不确定是否有更好的东西),最好在PHP.net上闲暇浏览功能列表边栏.只需阅读功能名称即可获得丰厚的回报.