2016-08-12 43 views
0

我有兩個數組,我想返回只包含在模板中的數組中的鍵:比較數組並放棄空值?

$protected template = ['name' => 'john', 'age'=> 10]; 

public function merge($params){ 

    $arr = array_intersect_key($params, $this->template); 

} 

上述作品,但我也想過濾掉鍵,該值爲空。

所以,如果我通過在:

[name => 'jeff', age => ''] 

它只會篩選出數組:

[name => 'jeff'] 

有沒有辦法做到這一點還是這將是最好只通過循環數組並做一個空的檢查?

回答

1

您可以使用array_filter刪除空的元素。

$template = array_filter($template, 'strlen') 
+2

這會在這種情況下刪除年齡['name'=>'john','age'=>'0']; – jonju

+1

你確定嗎? http://sandbox.onlinephpfunctions.com/code/d90c1c83f0a44668b5240cfd02d826576b838d49 – Whiteulver

+0

是的,我。你需要一個回調函數來處理這 – jonju