我有两个结构几乎相同的数组。
第一个数组是$_POST
数据,而第二个数组包含正则表达式规则和其他一些用于数据验证的东西。
例:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'someregex'
)
)
);
现在我想检查一下
$data['address']['city'] with $structure['address']['city']['regex']
或
$data['foo']['bar']['baz']['xyz'] with $structure['foo']['bar']['baz']['xyz']['regex']
任何想法如何使用PHP函数实现这一点?
编辑:似乎我自己找到了解决方案。
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'mail' => 'test@test.tld'
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'some_city_regex1',
)
),
'mail' => array(
'regex' => 'some_mail_regex1',
)
);
function getRegex($data, $structure)
{
$return = false;
foreach ($data as $key => $value) {
if (empty($structure[$key])) {
continue;
}
if (is_array($value) && is_array($structure[$key])) {
getRegex($value, $structure[$key]);
}
else {
if (! empty($structure[$key]['regex'])) {
echo sprintf('Key "%s" with value "%s" will be checked with regex "%s"', $key, $value, $structure[$key]['regex']) . '<br>';
}
}
}
return $return;
}
getRegex($data, $structure);
给定这些数组:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => 'hij'
)
)
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => '[a-Z]'
)
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => array(
'regex' => '[0-9]+'
)
)
)
)
);
和这个函数:
function validate ($data, $structure, &$validated) {
if (is_array($data)) {
foreach ($data as $key => &$value) {
if (
array_key_exists($key, $structure)
and is_array($structure[$key])
) {
if (array_key_exists('regex', $structure[$key])) {
if (!preg_match($structure[$key]['regex'])) {
$validated = false;
}
}
validate($value, $structure[$key], $validated);
}
}
}
}
您可以相互检查数组并获得如下所示的验证结果:
$validated = true;
validate($data, $structure, $validated);
if ($validated) {
echo 'everything validates!';
}
else {
echo 'validation error';
}
啊,你已经找到了解决方案。很好。