PHP introductory filtering for complex arrays

The official PHP documentation states that filter_var_array() supports filtering arrays in the following format:

 $data = array( 'testarray' => array('2', '23', '10', '12') ); $args = array( 'testarray' => array('filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_FORCE_ARRAY ) ); $myinputs = filter_var_array($data, $args); 

However, if the array in question is multidimensional and requires different filters for different parts, how do you approach the definition of filtering parameters?

As an example:

 $data = array( 'testhash' => array('level1'=>'email', 'level2'=> array('23', '10', '12')) ); 
+7
source share
1 answer

Idea 1

Consider using FILTER_CALLBACK. So you can write a callback function that itself uses a filter extension, thereby providing recursive ability.

 function validate_array($args) { return function ($data) use ($args) { return filter_input_array($data, $args); }; } 

This will call the callback functions.

 $args = array( 'user' => array( 'filter' => FILTER_CALLBACK, 'options' => validate_array(array( 'age' => array('filter' => FILTER_INPUT_INT), 'email' => array('filter' => FILTER_INPUT_EMAIL) )) ) ); 

Then the configuration array will look.

Idea 2

Feel free to pat me on the back, because I'm very proud of it.

Take an arg array that looks like this. Slashes indicate depth.

 $args = array( 'user/age' => array('filter' => FILTER_INPUT_INT), 'user/email' => array('filter' => FILTER_INPUT_EMAIL), 'user/parent/age' => array('filter' => FILTER_INPUT_INT), 'foo' => array('filter' => FILTER_INPUT_INT) ); 

Suppose your data looks something like this.

 $data = array( 'user' => array( 'age' => 15, 'email' => ' foo@gmail.com ', 'parent' => array( 'age' => 38 ) ), 'foo' => 5 ); 

You can then create an array of links that display keys such as user / age in $ data ['user'] ['age']. In the final production, you get something like this:

 function my_filter_array($data, $args) { $ref_map = array(); foreach ($args as $key => $a) { $parts = explode('/', $key); $ref =& $data; foreach ($parts as $p) $ref =& $ref[$p]; $ref_map[$key] =& $ref; } return filter_var_array($ref_map, $args); } var_dump(my_filter_array($data, $args)); 

Now the only question is how do you deal with the mismatch between the validation record and the original dataset. I cannot answer this without knowing how you need to use them.

+11
source

All Articles