我有一個動態生成的文件名的排列,讓我們說這看起來是這樣的:刪除從PHP數組的多個元素的有效方式
$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";
所以,我會一直知道我想丟棄的元素的值,但不是密鑰。
目前我正在看幾種方法來做到這一點。 一種方法,使用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"));
的另一種方式,using array_keys and 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);
這兩種方式產生所需的結果。
我只是想知道哪一個會更有效率(以及爲什麼)?
或者也許有另一種更有效的方法來做到這一點?
也許有一種方法可以在array_search函數中有多個搜索值?
嗨Feanne - 無需改變標題,一旦你找到了可以接受的答案。 StackOverflow照顧所有,一旦你打到綠色複選標記:) – 2012-04-10 14:22:07
注意到,謝謝你@MikeB :) – Feanne 2012-04-10 14:26:57