2012-12-17 88 views
1

我有以下POST數組:PHP:過濾多維POST陣列

[projects] => Array (
     [0] => Array 
      (
       [description] => description 1 
       [path] => url 1 
      ) 

     [1] => Array 
      (
       [description] => description2 
       [path] => url 2 
      ) 

     [2] => Array 
      (
       [description] => description 3 
       [path] => url 3 
      ) 

    ) 

我希望它與filter_var_array($_POST, $this -> fields);其中字段= array('projects' => array('filter' => FILTER_CALLBACK,'flags' => FILTER_FORCE_ARRAY, 'options' => array($this, 'cleanProjects'));

但是,值傳遞給cleanProjects功能被過濾不是包含描述和路徑的數組,但它將所有值逐個傳遞(所以方法被稱爲六次,描述1的描述爲1,描述1爲1,描述2的描述爲1)。

我有過濾器嗎?函數將整個對象傳遞給回調函數? 因此,它會爲項目中的每個對象/數組調用cleanProjects(在本例中爲3次)。

+1

如果你只想調用一次,爲什麼還要用'filter_var'呢?爲什麼不做'$ this-> cleanProjects($ _ POST ['projects']);'? – DaveRandom

+0

我希望每個項目都能調用一次。整個帖子更大,項目只是其中的一個領域。 – rsids

回答

0

你現在使用什麼叫做Indirect method call by array variable其只能通過PHP 5.4 above

解決方案1的支持:升級你的PHP版本和您的代碼會用了修改

 'options' => array($this, 'cleanProjects'))); 
         |_______________________| 
             +------------ Indirect Method call by array 

方案2的工作:只需使用Closures

$self = $this ; 
    $options = function($args) use ($self) 
    { 
     $self->cleanProjects($args); 
    }; 

    $this->fields = array('projects' => array(
      'filter' => FILTER_CALLBACK, 
      'flags' => FILTER_FORCE_ARRAY, 
      'options' => $options)); // add the closure 
    $var = filter_var_array($_POST, $this -> fields); 
+0

1.我正在運行5.4,2.問題不在於該方法未被調用,而是經常調用該方法。 – rsids

+0

是的,它會在每個參數上調用回調的工作方式 – Baba

+0

但是不應該在每個項目項目上調用它(不是項目中每個項目的每個字段)? – rsids