2012-04-10 57 views
7

我有一個動態生成的文件名的排列,讓我們說這看起來是這樣的:刪除從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函數中有多個搜索值?

+0

嗨Feanne - 無需改變標題,一旦你找到了可以接受的答案。 StackOverflow照顧所有,一旦你打到綠色複選標記:) – 2012-04-10 14:22:07

+0

注意到,謝謝你@MikeB :) – Feanne 2012-04-10 14:26:57

回答

17

您只需要使用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); 

之一壞話PHP的是,它具有的功能,做具體的小事情不計其數,但也可以變成方便的時候。

當你遇到這樣的情況時(你找到了相關函數後找到了解決方案,但你不確定是否有更好的方法),在php.net上瀏覽函數列表邊欄是個好主意休閒。只是閱讀函數名稱可以支付巨大的紅利。

+0

非常感謝@Jon - 我會記住你的建議。我在閒暇時閱讀函數列表,但從未注意過「差異」函數,因爲我無法想象我將如何使用它們......現在我知道了更好! :) – Feanne 2012-04-10 14:18:11

+0

如果這些元素不是字符串而是對象或數組呢?我想刪除那些具有一些屬性eqlual到'a'和'b'的元素,例如? – Herokiller 2015-11-02 10:34:29

+0

@Herokiller在這種情況下,你需要使用'array_filter'。 – Jon 2015-11-02 11:26:52

1

使用和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"); 

將返回從$ exclude_file_array不在$文件中的所有元素的數組。

$new_array = array_diff($files, $exclude_file_array); 

它比你自己的函數和循環更好。

+0

謝謝,已經指出這一點,我已經在我的代碼中實現了它。 – Feanne 2012-04-10 14:27:53

+0

不客氣@費恩恩喬恩說,首先瀏覽php.net這將是偉大的..好工作。 – 2012-04-10 14:32:39

相關問題