复杂数组的 PHP 输入过滤 [英] PHP input filtering for complex arrays
问题描述
官方 PHP 文档声明 filter_var_array()
支持以下格式的数组过滤:
Official PHP documentation states that filter_var_array()
supports array filtering 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 multi-dimensional and requires different filters for different parts, how would you approach defining filtering options?
举个例子:
$data = array(
'testhash' => array('level1'=>'email',
'level2'=> array('23', '10', '12'))
);
推荐答案
Idea 1
考虑使用 FILTER_CALLBACK.这样就可以编写一个回调函数,本身使用过滤器扩展,从而提供递归能力.
Consider using FILTER_CALLBACK. In this way, you can write a callback function that itself uses the filter extension, thus providing a recursive ability.
function validate_array($args) {
return function ($data) use ($args) {
return filter_input_array($data, $args);
};
}
这将生成回调函数.
$args = array(
'user' => array(
'filter' => FILTER_CALLBACK,
'options' => validate_array(array(
'age' => array('filter' => FILTER_INPUT_INT),
'email' => array('filter' => FILTER_INPUT_EMAIL)
))
)
);
这就是配置数组的样子.
This is what the config array would then look like.
想法 2
不要犹豫,为这个拍拍我的背,因为我为此感到非常自豪.
Do not hesitate to pat me on the back for this one because I am quite proud of it.
取一个看起来像这样的 arg 数组.斜线表示深度.
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)
);
假设您的数据看起来像这样.
Assume your data looks something like this.
$data = array(
'user' => array(
'age' => 15,
'email' => 'foo@gmail.com',
'parent' => array(
'age' => 38
)
),
'foo' => 5
);
然后,您可以生成一个引用数组,将诸如 'user/age' 之类的键映射到 $data['user']['age'].在最终制作中,您会得到如下内容:
Then, you can generate an array of references that map keys such as 'user/age' to $data['user']['age']. In 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 you deal with the mismatch between the validation record and the original data set. This I cannot answer without knowing how you need to use them.
这篇关于复杂数组的 PHP 输入过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!