2016-11-20 129 views
1

我有數組,其中有很多空字段。我如何刪除填充字段,並使用空字段創建新數組。 因此,例如:選擇鍵值爲空的鍵/ array/php

[0] => Array 
     (
      [id] => 26 
      [user_type] => 2 
      [user_name] => Julian 
      [password] => b941da1629f4742de62796d51730edbb 
      [fpassword] => 1 
      [email] => [email protected] 
      [name] => 
      [surname] => 
      [birthday] => 0000-00-00 
      [country] => 
      [city] => 
      [adress] => 
      [post_code] => 
      [mob_number] => 77077412 
      [tel_number] => 0 
      [web_page] => 
      [registration_date] => 2016-11-19 05:03:05 
      [active] => 1 
      [activation_code] => 714779 
      [last_login] => 2016-11-20 12:06:36 
     ) 

所以,我想這一點:

[0] => Array 
     (
      [name] => 
      [surname] => 
      [birthday] => 0000-00-00 
      [country] => 
      [city] => 
      [adress] => 
      [post_code] => 
      [tel_number] => 0 
      [web_page] => 

     ) 

我累array_diff($data, array(''));,但沒有happend.Thx

回答

0

你可以做這樣的事情,在$a1 - 只是讓你想在新的數組,看看哪個值的規則。

$a1 = array('empty' => '', 'another_rule' => '0000-00-00'); 
$a2 = array(
      'id' => 26, 
      'user_type' => 2, 
      'name' => '', 
      'birthday' => '0000-00-00', 
     ); 
$result = array_intersect($a2, $a1); 
+0

工作!你太好了! –

3

你需要一個 「反向」 array_filter,如:

$empty = array_filter($data, function($item) { 
    return empty($item); 
}); 

但它需要調整爲各種值,爲示例日期0000-00-00不是「虛假」,因此它不會被empty捕獲。規則是你需要從array_filter的可調用函數返回任何你認爲是「空」的值。

你在這個例子中所需要的代碼將是:

$data = [ 
    'int' => 100, 
    'str' => 'val', 
    'empty' => '', 
    'null' => null, 
    'date' => '0000-00-00', 
]; 
$empty = array_filter($data, function($item) { 
    return empty($item) || '0000-00-00' === $item; 
});